JSON使用

  1. 泛型反序列化

new TypeReference<List<User>>()
2. 如果数据对象中存在Map对象,为了保证序列化后的字段顺序一致,需要添加SerializerFeature.MapSortField特征。

1
JSON.toJSONString(userMap, SerializerFeature.MapSortField);
  1. 排除所有类的属性字段:

    1
    List<UserVO> userList = ...;SimplePropertyPreFilter filter = new SimplePropertyPreFilter();filter.getExcludes().addAll(Arrays.asList("gmtCreate", "gmtModified"));Assert.assertEquals("用户信息不一致", text, JSON.toJSONString(user, filter));

排除单个类的属性字段:

1
List<UserVO> userList = ...;SimplePropertyPreFilter filter = new SimplePropertyPreFilter(UserVO.class);filter.getExcludes().addAll(Arrays.asList("gmtCreate", "gmtModified"));Assert.assertEquals("用户信息不一致", text, JSON.toJSONString(user, filter));

排查多个类属性:

1
2
3
4
5
6
7
java
Pair<UserVO, CompanyVO> userCompanyPair = ...;
SimplePropertyPreFilter userFilter = new SimplePropertyPreFilter(UserVO.class);
userFilter.getExcludes().addAll(Arrays.asList("gmtCreate", "gmtModified"));
SimplePropertyPreFilter companyFilter = new SimplePropertyPreFilter(CompanyVO.class);
companyFilter.getExcludes().addAll(Arrays.asList("createTime", "modifyTime"));
Assert.assertEquals("用户公司对不一致", text, JSON.toJSONString(userCompanyPair, new SerializeFilter[]{userFilter, companyFilter});