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的属性。

猜你喜欢

转载自www.cnblogs.com/theRhyme/p/10339071.html