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


 

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM