一個pojo類:
import lombok.Data; @Data public class Friend { private String name; private int age; private String sex; }
初始化一個Friend對象,該對象屬性為"sex"對應的值設置為null:
public class FriendTest { private Friend friend = new Friend(); @Before public void init(){ friend.setAge(26); friend.setName("xiaofang"); friend.setSex(null); }
使用FastJson將該對象轉化為Json字符串:
@Test public void testObjectToJson(){ String jsonString = JSONObject.toJSONString(friend); System.out.println(jsonString); }
可以看到,"sex"字段由於為null,轉化時該字段沒了。
設置序列化類型
@Test public void testJsonSerializer(){ String jsonString = JSONObject.toJSONString(friend, SerializerFeature.WriteMapNullValue); System.out.println(jsonString); }
就有值為null的屬性了。
RestTemplate傳輸值為null的屬性
使用RestTemplate傳輸該Friend對象時,值為null的屬性會被忽略掉,但是我們在某些情況下想要傳輸值為null的屬性,我們可以在該字段上加上com.fasterxml.jackson.annotation.@JsonInclude注解,通過RestTemplate傳輸,就不會忽略值為null的屬性。