如何透過使用 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