如何通过使用 JsonConfig 中的排除属性来将 Bean 转换为 JSON 对象?
JsonConfig 类是一个有助于配置序列化过程的工具类。我们可以使用 JsonConfig 类的 setExcludes() 方法从一个 Bean 转换一个 JSON 对象,并从 JSONObject 的 static 方法 fromObject() 获取一个 JSON 配置实例作为参数。
语法
public void setExcludes(String[] excludes)
在下面的示例中,我们可以通过排除某些属性从一个 Bean 转换一个 JSON 对象。
示例
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
public class BeanToJsonExcludeTest {
public static void main(String[] args) {
Student student = new Student("Raja", "Ramesh", 35, "Madhapur");
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setExcludes(new String[]{"age", "address"});
JSONObject obj = JSONObject.fromObject(student, jsonConfig);
System.out.println(obj.toString(3)); //pretty print JSON
}
public static class Student {
private String firstName, lastName, address;
private 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;
}
}
}在下面的输出中,age 和 address 属性已被排除。
输出
{
"firstName": "Raja",
"lastName": "Ramesh"
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
JavaScript
PHP