fastjson的JSONString()默认忽略值为null的属性
现象
使⽤ fastjson 的 JSONString() 将实体对象转成 JSON 字符串时,部分属性莫名其妙地消失了,影响后续的使⽤。⽰例代码
@Test
public void testNoNull(){
Person person =new Person();
person.setName("jia");
person.setAge(6);
person.setArea("上海长宁");
System.out.JSONString(person));
}
public class Person {
private String name;
private int age;
private String area;
private String like;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
public String getArea(){
return area;
}
public void setArea(String area){
this.area = area;
}
public String getLike(){
return like;
}
public void setLike(String like){
this.like = like;
}
}
输出结果
{"age":6,"area":"上海长宁","name":"jia"}
由上可知,输出结果中不包含 “like” 属性。
原因
fastjson 的 JSONString() 默认忽略值为 null 的属性。
解决⽅案
设置 fastjson 的 SerializerFeature 的值为 WriteMapNullValue,输出值为 null 的属性。
⽰例代码
@Test
public void testWithNull(){
Person person =new Person();
person.setName("jia");
person.setAge(6);
person.setArea("上海长宁");
System.out.JSONString(person, SerializerFeature.WriteMapNullValue));
}
输出结果
{"age":6,"area":"上海长宁","like":null,"name":"jia"}
拓展
JSON 的 public static String toJSONString(Object object, SerializerFeature… features) ⽅法中可以接收多个 SerializerFeature 类型的参数;⽽ SerializerFeature 是枚举类型,定义的枚举对象如下:
public enum SerializerFeature {
QuoteFieldNames,
UseSingleQuotes,
WriteMapNullValue,
WriteEnumUsingToString,
WriteEnumUsingName,
UseISO8601DateFormat,
WriteNullListAsEmpty,
WriteNullStringAsEmpty,
WriteNullNumberAsZero,
WriteNullBooleanAsFalse,
SkipTransientField,
SortField,
/** @deprecated */
@Deprecated
WriteTabAsSpecial,
PrettyFormat,
object toWriteClassName,
DisableCircularReferenceDetect,
WriteSlashAsSpecial,
BrowserCompatible,
WriteDateUseDateFormat,
NotWriteRootClassName,
/** @deprecated */
DisableCheckSpecialChar,
BeanToArray,
WriteNonStringKeyAsString,
NotWriteDefaultValue,
BrowserSecure,
IgnoreNonFieldGetter,
WriteNonStringValueAsString,
IgnoreErrorGetter,
WriteBigDecimalAsPlain,
MapSortField;
/**
* 省略其它代码
* /
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。