首页 > 代码库 > json-lib过滤属性
json-lib过滤属性
依赖jar:
commons-beanutils-1.9.3.jar?
commons-collections-3.1.jar
commons-lang-2.4.jar
commons-logging-1.2.jar
ezmorph-1.0.6.jar
json-lib-2.4-jdk15.jar
直接上程序
1、Person.java:
import java.util.List;
/**
* Created by Administrator on 2017/5/6.
*/
public class Person {
private int id;
private String name;
private List<Address> addresses;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Address> getAddresses() {
return addresses;
}
public void setAddresses(List<Address> addresses) {
this.addresses = addresses;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name=‘" + name + ‘\‘‘ +
", addresses=" + addresses +
‘}‘;
}
}
2、Address.java:
public class Address {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Address{" +
"name=‘" + name + ‘\‘‘ +
‘}‘;
}
}
3、测试程序
Person person = new Person();
person.setId(1);
person.setName("xiaoming");
List<Address> addresses = new ArrayList<Address>();
Address address = new Address();
address.setName("xian");
addresses.add(address);
person.setAddresses(addresses);
//设置过滤字段 方法1 使用setJsonPropertyFilter
JsonConfig jsonConfig = new JsonConfig();
PropertyFilter filter = new PropertyFilter() {
//参数1:person对象 如果有两个fieldName都是name,则都会被过滤,无法精确控制
public boolean apply(Object object, String fieldName, Object fieldValue) {
return fieldName.equals("name");
}
};
jsonConfig.setJsonPropertyFilter(filter);
System.out.println(JSONObject.fromObject(person, jsonConfig).toString());
//方法2 过滤id
jsonConfig.setExcludes(new String[]{"id"}); //java
说明:
这两这种方法,如果出现多个相同属性,设置了过滤后,会全部过滤掉,无法精确控制具体哪一个属性。
json-lib过滤属性
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。