1. 程式人生 > >RestTemplate傳輸值為null的屬性、利用FastJson將屬性中有空值null的對象轉化成Json字符串

RestTemplate傳輸值為null的屬性、利用FastJson將屬性中有空值null的對象轉化成Json字符串

但是 emp bubuko 屬性 pojo ets 傳輸 情況 system

一個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的屬性。

RestTemplate傳輸值為null的屬性、利用FastJson將屬性中有空值null的對象轉化成Json字符串