JSONObject.toBean() chuyển JSONObject → Java Bean (class có getter/setter). JSON-lib đã cũ, khuyến nghị dùng Jackson/Gson.
Cú pháp
public static Object toBean(JSONObject jsonObject, Class beanClass)
Ví dụ minh họa
import net.sf.json.JSONObject;
public class JsonObjToBeanTest {
public static void main(String[] args) {
Employee emp = new Employee("Sai", "Ram", 30, "Bangalore");
// Bean → JSONObject
JSONObject jsonObj = JSONObject.fromObject(emp);
System.out.println("JSON: " + jsonObj.toString(3));
// JSONObject → Bean
emp = (Employee) JSONObject.toBean(jsonObj, Employee.class);
System.out.println("Bean: " + emp.toString());
}
static class Employee {
private String firstName, lastName, address;
private int age;
public Employee() {}
public Employee(String fn, String ln, int age, String addr) {
this.firstName = fn; this.lastName = ln; this.age = age; this.address = addr;
}
// Getters/Setters...
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; }
@Override
public String toString() {
return "Employee[firstName=" + firstName + ", lastName=" + lastName +
", age=" + age + ", address=" + address + "]";
}
}
}
Output
{
"firstName": "Sai",
"lastName": "Ram",
"address": "Bangalore",
"age": 30
}
Employee[firstName=Sai, lastName=Ram, age=30, address=Bangalore]
Tương đương với Jackson (Khuyến nghị)
ObjectMapper mapper = new ObjectMapper();
// Bean → JSON
String json = mapper.writeValueAsString(emp);
// JSON → Bean
Employee emp2 = mapper.readValue(json, Employee.class);
Lưu ý
- Bean phải có **no-arg constructor** và **setter** cho từng field.
- JSON-lib map theo tên field (bỏ prefix get/set, lowercase first letter).
- Type mismatch: JSON-lib cố gắng convert (String→int, etc) nhưng có thể fail.
- Không dùng JSON-lib cho dự án mới - thư viện unmaintained, security risk.