如何使用 Exclude Filter 在 Java 中将 Bean 转换成 JSON 对象?
可以使用 JsonConfig 类配置序列化过程。在序列化到 JSON 时,可以使用 JsonConfig 的 setJsonPropertyFilter() 方法设置属性过滤器。我们需覆盖 PropertyFilter 接口的 apply() 方法实现一个自定义 PropertyFilter 类。如果将过滤掉该属性,它会返回 true;否则返回 false。
语法
public void setJsonPropertyFilter(PropertyFilter jsonPropertyFilter)
示例
import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import net.sf.json.util.PropertyFilter; public class ConvertBeanToJsonExcludeFilterTest { public static void main(String[] args) { Student student = new Student("Sai", "Chaitanya", 20, "Hyderabad"); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJsonPropertyFilter(new CustomPropertyFilter()); JSONObject jsonObj = JSONObject.fromObject(student, jsonConfig); System.out.println(jsonObj.toString(3)); //pretty print JSON } public static class Student { private String firstName, lastName, address; public int age; public Student(String firstName, String lastName, int age, String address) { super(); this.firstName = firstName; this.lastName = lastName; this.age = age; this.address = address; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getAge() { return age; } public String getAddress() { return address; } } } // CustomPropertyFilter class class CustomPropertyFilter implements PropertyFilter { @Override public boolean apply(Object source, String name, Object value) { if(Number.class.isAssignableFrom(value.getClass()) || String.class.isAssignableFrom(value.getClass())) { return false; } return true; } }
输出
{ "firstName": "Sai", "lastName": "Chaitanya", "address": "Hyderabad", "age": 20 }
广告