用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,要怎么写。关键就是这里属性名重了

 

如果要采纳请采纳xiaoyu1985ban

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);

[code="java"]
你这样过滤, 对于json来说,他分不清你传来的是a还是b, 或者c对象等
他只是对你传来的任何一个对象只要有a属性, 他就过滤

[/code]

先不过滤,获取jsonObject后调用jsonObject.remove("a");删除这个属性

解析成的json应该是
[code="js"]{"a":"","b":{a:""}}[/code]

这个没必要过滤吧

题主,可以试试PropertyFilter,
[code="java"]//创建A对象
A target = new A();
target.setA("a");
B b = new B();
b.setA("b.a");
target.setB(b);
JsonConfig config = new JsonConfig();
//配置Filter
config.setJsonPropertyFilter(new PropertyFilter() {

        @Override
        public boolean apply(Object source, String name , Object value) {               
            //过滤条件:返回true时,过滤生效
            return source instanceof A && name.equals("a");  
        }
    });

    JSON json = JSONSerializer.toJSON( target, config );

    String out = json.toString();
    System.out.println(out); // {"b":{"a":"b.a"}}
    //不过滤的结果:{"a":"a","b":{"a":"b.a"}}[/code]