fastjson git地址:https://github.com/alibaba/fastjson/wiki
SimplePropertyPreFilter 用法
用于过滤某个属性
SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
filter.getExcludes().add("gender");
A a = new A(1,"zhangsan","gender");
String json = JSON.toJSONString(a,filter);
System.out.println(json);
过滤gender属性
过滤name属性
PropertyFilter
也可以自己写 PropertyFilter
其中object 是要转成json的对象,name是属性名,value是属性值,可以根据自己的需求自定义
SimplePropertyPreFilter 实现了 PropertyPreFilter
return true表示会返回回来;return false表示过滤掉了
当然new PropertyFilter()也可以改成lambda的形式,那么更简介
PropertyFilter propertyFilter = new PropertyFilter() {
@Override
public boolean apply(Object object, String name, Object value) {
if(name.equals("gender")){
return true;
}
return false;
}
};
A a = new A(2, "lisi", "男");
String json = JSON.toJSONString(a,propertyFilter);
System.out.println(json);
类过滤器
Class_Level_SerializeFilter · alibaba/fastjson Wiki · GitHub
NameFilter
对属性名进行修改
把所有属性名都大写
NameFilter nameFilter = new NameFilter() {
@Override
public String process(Object object, String name, Object value) {
return name.toUpperCase();
}
};
// 对A类添加过滤器
SerializeConfig.getGlobalInstance().addFilter(A.class, nameFilter);
A a = new A(3,"wangwu","女");
String s = JSON.toJSONString(a);
System.out.println(s);
ValueFilter
对value进行修改
ValueFilter valueFilter = (object, name, value) -> name + "-" + value;
SerializeConfig.getGlobalInstance().addFilter(A.class, valueFilter);
A a = new A(4,"zhaoliu","女");
String s = JSON.toJSONString(a);
System.out.println(s);
NameFilter和ValueFilter都实现了SerializeFilter
SerializeFilter · alibaba/fastjson Wiki · GitHub
版权归原作者 CelineT 所有, 如有侵权,请联系我们删除。