fastjson中的null问题:
QuoteFieldNames——输出key时是否使用双引号,默认为true
WriteMapNullValue——是否输出值为null的字段,默认为false
WriteNullNumberAsZero——数值字段如果为null,输出为0,而非null
WriteNullListAsEmpty——List字段如果为null,输出为[],而非null
WriteNullStringAsEmpty——字符类型字段如果为null,输出为”“,而非null
WriteNullBooleanAsFalse——Boolean字段如果为null,输出为false,而非null
fastjson中的时间格式问题:
JSON.DEFFAULT_DATE_FORMAT = “yyyy-MM-dd HH:mm:ss(你要设定的日期格式)”
fastjson中list集合中有重复元素问题 :
DisableCircularReferenceDetect——解决list中重复元素无法读取的bug
例子:
@Test
public void doT() {
List li = new ArrayList();
Teacher tea = new Teacher();
tea.setName("wang");
Teacher tea2 = new Teacher();
tea2.setName("wang");
Student stu = new Student();
stu.setAge(20);
stu.setTeacher(tea);
stu.setSex("nan");
li.add(stu);
li.add(stu);
Result re = new Result();
re.setError("1");
re.setObj(li);
//时间格式设置
JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
System.out.println(
JSON.toJSONString(
//re为要转的对象
re,
//WriteDateUseDateFormat--时间格式
SerializerFeature.WriteDateUseDateFormat,
//WriteMapNullValue--是否输出值为null的值,默认是false,配上后能输出
SerializerFeature.WriteMapNullValue,
//WriteNullListAsEmpty--当list为null时,输出为[]
SerializerFeature.WriteNullListAsEmpty,
//DisableCircularReferenceDetect--解决list中有重复元素问题
SerializerFeature.DisableCircularReferenceDetect
)
);
}
fastjson中不需要被格式化的属性问题
@JSONField——是fastjson中的一个注解。在属性头上加上这个注解中,在对对象进行json转换时,该属性,将不会参与格式化。
例子:
//如果前端需要的是大写的参数,json会按默认的将大写的参数在最后返回给前端时转化为小写,这时候设置一下@JSONField,使前端拿到的参数还是大写的。
@JSONField(name = "ErrorCode")
private int ErrorCode;
fastjson反序列化中的问题
问题描述:
com.alibaba.fastjson.JSONObject cannot be cast to XXX,意思是说JSONObject 不能转成我想要的对象,很明显是因为少了一个属性authorityUri,因为他是null,在反序列化的时候出现了错误。
public class RoleAuthorityUri {
private String roleid;
private List<Authority> list;
}
public class Authority {
private String authorityId;
private String authorityName;
private String authorityUri;
public String getAuthorityId() {
return authorityId;
}
public void setAuthorityId(String authorityId) {
this.authorityId = authorityId == null ? null : authorityId.trim();
}
public String getAuthorityName() {
return authorityName;
}
public void setAuthorityName(String authorityName) {
this.authorityName = authorityName == null ? null : authorityName.trim();
}
public String getAuthorityUri() {
return authorityUri;
}
public void setAuthorityUri(String authorityUri) {
this.authorityUri = authorityUri == null ? null : authorityUri.trim();
}
@Override
public String toString() {
return "Authority{" +
"authorityId='" + authorityId + '\'' +
", authorityName='" + authorityName + '\'' +
", authorityUri='" + authorityUri + '\'' +
'}';
}
}
str中的是RoleAuthorityUri对象的json字符串,但是list(Authority对象)中的authorityUri暂时还都是null,然后将str反序列化成为RoleAuthorityUri对象之后,authorityUri属性就不见了- - - 这是什么鬼0.0
存入的时候是没问题的,str也打印出来了,但是为什么反序列化之后就没有这个属性了呢???求助于各路大神
本人的解决方法(可能有点蠢):直接转成RoleAuthorityUri对象,来拿list,不通过JsonObject对象