json复杂对象处理jsonConfig
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 );
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。