SerializeFilter 是通过编程扩展的方式定制序列化。Fastjson 支持如下6种 SerializeFilter,用于不同场景的定制序列化。
- PropertyPreFilter:根据 PropertyName 判断是否序列化;
- PropertyFilter:根据 PropertyName 和 PropertyValue 来判断是否序列化;
- NameFilter:修改 Key,如果需要修改 Key,process 返回值则可;
- ValueFilter:修改 Value;
- BeforeFilter:序列化时在最前添加内容;
- AfterFilter:序列化时在最后添加内容;
需求
JSON 数据格式如下,需要过滤掉其中 “book” 的 “price” 属性。
JSON 数据格式:
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}
SimplePropertyPreFilter 过滤器
该过滤器由 Fastjson 提供,测试代码如下:
String json = "{\"store\":{\"book\":[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99}],\"bicycle\":{\"color\":\"red\",\"price\":19.95}},\"expensive\":10}";
SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
filter.getExcludes().add("price");
JSONObject jsonObject = JSON.parseObject(json);
String str = JSON.toJSONString(jsonObject, filter);
System.out.println(str);
运行结果:
{
"store": {
"bicycle": {
"color": "red"
},
"book": [
{
"author": "Nigel Rees",
"category": "reference",
"title": "Sayings of the Century"
},
{
"author": "Evelyn Waugh",
"category": "fiction",
"title": "Sword of Honour"
}
]
},
"expensive": 10
}
查看 JSON 数据的过滤结果,发现 “bicycle” 中的 “price” 属性也被过滤掉了,不符合需求。
LevelPropertyPreFilter 过滤器
该自定义过滤器实现 PropertyPreFilter 接口,实现根据层级过滤 JSON 数据中的属性。
扩展类:
测试代码如下:
public static void main(String[] args) {
String json = "{\"store\":{\"book\":[{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"price\":8.95},{\"category\":\"fiction\",\"author\":\"Evelyn Waugh\",\"title\":\"Sword of Honour\",\"price\":12.99}],\"bicycle\":{\"color\":\"red\",\"price\":19.95}},\"expensive\":10}";
JSONObject jsonObj = JSON.parseObject(json);
LevelPropertyPreFilter propertyPreFilter = new LevelPropertyPreFilter();
propertyPreFilter.addExcludes("store.book.price");
String json2 = JSON.toJSONString(jsonObj, propertyPreFilter);
System.out.println(json2);
}
运行结果:
{
"store": {
"bicycle": {
"color": "red",
"price": 19.95
},
"book": [
{
"author": "Nigel Rees",
"category": "reference",
"title": "Sayings of the Century"
},
{
"author": "Evelyn Waugh",
"category": "fiction",
"title": "Sword of Honour"
}
]
},
"expensive": 10
}
查看 JSON 数据的过滤结果,实现了上面的需求。
参考:http://www.cnblogs.com/dirgo/p/5178629.html
作者:殷建卫 链接:https://www.yuque.com/yinjianwei/vyrvkf/zsi0fh 来源:殷建卫 - 架构笔记 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。