码迷,mamicode.com
首页 > Web开发 > 详细

json-lib过滤属性

时间:2017-05-07 15:42:47      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:beanutils   person   set   public   lang   create   nis   add   collect   

依赖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过滤属性

标签:beanutils   person   set   public   lang   create   nis   add   collect   

原文地址:http://www.cnblogs.com/liulongzhiyu/p/6819520.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!