(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 );
我们通常的Json字符串和java当对象互转。经常有选择性地过滤掉一些属性值,和json-lib包JsonConfig为我们提供了这样一个 特征,有几种方法实施细则。