@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);
}

@JsonInclude注解,RestTemplate传输值为null的属性,利用FastJson将属性中有空值null的对象转化成Json字符串

可以看到,"sex"字段由于为null,转化时该字段没了。

设置序列化类型

@Test
public void testJsonSerializer(){
String jsonString = JSONObject.toJSONString(friend, SerializerFeature.WriteMapNullValue);
System.out.println(jsonString);
}

@JsonInclude注解,RestTemplate传输值为null的属性,利用FastJson将属性中有空值null的对象转化成Json字符串

就有值为null的属性了。

RestTemplate传输值为null的属性

使用RestTemplate传输该Friend对象时,值为null的属性会被忽略掉,但是我们在某些情况下想要传输值为null的属性,我们可以在该字段上加上com.fasterxml.jackson.annotation.@JsonInclude注解,通过RestTemplate传输,就不会忽略值为null的属性。

上一篇:Linux实战教学笔记05:远程SSH连接服务与基本排错(新手扫盲篇)


下一篇:linux启动SSH及开机自动启动