咱們一般對一個Json串和java對象進行互轉時,常常會有選擇性的過濾掉一些屬性值,而json-lib包中的JsonConfig爲咱們提供了這種功能,具體實現方法有如下幾種。(1)創建JsonConfig實例,並配置屬性排除列表,(2)用屬性過濾器,(3)寫一個自定義的JsonBeanProcessor.
1. 實現JSONString接口的方法
public class Person implements JSONString {
private String name;
private String lastname;
private Address address;
// getters & setters
public String toJSONString() {
return "{name:'"+name+"',lastname:'"+lastname+"'}";
}
}
2.第二種方法經過jsonconfig實例,對包含和須要排除的屬性進行方便的添加或刪除
public class Person {
private String name;
private String lastname;
private Address address;
// getters & setters
}
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExclusions( new String[]{"address"});
Person bean = new Person("jack","li");
JSON json = JSONSerializer.toJSON(bean, jsonConfig);
3. 使用propertyFilter能夠容許同時對須要排除的屬性和類進行控制,這種控制還能夠是雙向的,也能夠應用到json字符串到java對象
public class Person {
private String name;
private String lastname;
private Address address;
// getters & setters
}
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setJsonPropertyFilter( new PropertyFilter(){
public boolean apply(Object source/* 屬性的擁有者 */, String name /*屬性名字*/, Object value/* 屬性值 */ ){
// return true to skip name
return source instanceof Person && name.equals("address");
}
});
Person bean = new Person("jack","li");
JSON json = JSONSerializer.toJSON( bean, jsonConfig )
4. 最後來看JsonBeanProcessor,這種方式和實現JsonString很相似,返回一個表明原來的domain類的合法JSONObject
public class Person {
private String name;
private String lastname;
private Address address;
// getters & setters
}
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonBeanProcessor( Person.class, new JsonBeanProcessor(){
public JSONObject processBean( Object bean, JsonConfig jsonConfig ){
if(!(bean instanceof Person)){
return new JSONObject(true);
}
Person person = (Person) bean;
return new JSONObject() .element( "name", person.getName()) .element( "lastname", person.getLastname());
}
});
Person bean = new Person("jack","li"); JSON json = JSONSerializer.toJSON( bean, jsonConfig );