用JSON过滤对象中属性名相同时都会被过滤的情况,
我有一个需求:
class A {
private String a;
private B b;
//set/get方法省略
}
class B {
private String a;
//set/get方法省略
}
//过滤不需要解析的属性
JsonConfig config = new JsonConfig();
A target = new A();
config.setExcludes(new String[]{“a”});
JSONObject jsonObject = JSONObject.fromObject(target, config);
String out = jsonObject.toString();
这样后A类中过滤了a属性,同时对象b中的属性a也会被过滤掉,如果我只想过滤A类中的属性a,不想过来属性b对象中的属性a,要怎么写。关键就是这里属性名重了
采纳的答案:
JsonConfig config = new JsonConfig();
B b=new B();
b.setA(“a”);
A target = new A();
target.setA(“a”);
target.setB(b);
config.setJsonPropertyFilter( new PropertyFilter(){
public boolean apply(Object source/* 属性的拥有者 /, String name /属性名字/, Object value/ 属性值 */ ){
// return true to skip name
return source instanceof A&& name.equals(“a”);
}
});
JSONObject jsonObject = JSONObject.fromObject(target, config);
String out = jsonObject.toString();
System.out.println(out);