如何使用 Java 中的 JSON-lib API 將 JSON 物件轉換為 Bean?
JSONObject class 是一個名稱/值對的集合(無序),而bean是一個 class,其中包含成員欄位的setter和getter方法。我們可以使用JSONObject類的toBean()方法將一個 JSON 物件轉換為一個 bean。
語法
public static Object toBean(JSONObject jsonObject, Class beanClass)
示例
import net.sf.json.JSONObject;
public class ConvertJSONObjToBeanTest {
public static void main(String[] args) {
mployee emp = new Employee("Sai", "Ram", 30, "Bangalore");
JSONObject jsonObj = JSONObject.fromObject(emp);
System.out.println(jsonObj.toString(3)); // pretty print JSON
emp = (Employee)JSONObject.toBean(jsonObj, Employee.class);
System.out.println(emp.toString());
}
// Employee class
public static class Employee {
private String firstName, lastName, address;
private int age;
public Employee() {
}
public Employee(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 void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String toString() {
return "Employee[ " +
"firstName = " + firstName +
", lastName = " + lastName +
", age = " + age +
", address = " + address +
" ]";
}
}
}輸出
{
"firstName": "Sai",
"lastName": "Ram",
"address": "Bangalore",
"age": 30
}
Employee[ firstName = Sai, lastName = Ram, age = 30, address = Bangalore ]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP