JSONObject 클래스는 이름/값의 모음입니다. 쌍(순서 없음 ) 여기서 빈 setter 가 있는 클래스입니다. 및 게터 멤버 필드에 대한 메서드. toBean()을 사용하여 JSON 객체를 Bean으로 변환할 수 있습니다. JSONObject 메소드 수업.
구문
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 ]