我们通常对一个json串和java对象进行互转时,经常会有选择性的过滤掉一些属性值。例如下面的类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
public class Person
{
private String name;
private String address;
private String sex;
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getSex()
{
return sex;
}
public void setSex(String sex)
{
this.sex = sex;
}
}
|
如果我想过滤address属性怎么办?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
import net.sf.json.JSONString;
public class Person implements JSONString
{
private String name;
private String sex;
private String address;
public String toJSONString()
{
return "{\"name\":\"" + name + "\",\"sex\":\"" + sex + "\"}";
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getSex()
{
return sex;
}
public void setSex(String sex)
{
this.sex = sex;
}
}
import net.sf.json.JSONObject;
public class Test {
public static void main(String args[]) {
Person person = new Person();
person.setName("swiftlet");
person.setSex("men");
person.setAddress("china");
JSONObject json = JSONObject.fromObject(person);
System.out.println(json.toString());
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
public class Test
{
public static void main(String args[])
{
Person person = new Person();
person.setName("swiftlet");
person.setSex("men");
person.setAddress("china");
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(new String[]
{ "address" });
JSONObject json = JSONObject.fromObject(person, jsonConfig);
System.out.println(json.toString());
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;
public class Test
{
public static void main(String args[])
{
Person person = new Person();
person.setName("swiftlet");
person.setSex("men");
person.setAddress("china");
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
public boolean apply(Object source, String name, Object value)
{
return source instanceof Person && name.equals("address");
}
});
JSONObject json = JSONObject.fromObject(person, jsonConfig);
System.out.println(json.toString());
}
}
|
原文:http://www.cnblogs.com/doudouxiaoye/p/5693340.html