Computer >> Máy Tính >  >> Lập trình >> Java

Làm cách nào để chuyển đổi đối tượng JSON thành bean bằng cách sử dụng JSON-lib API trong Java?


JSONObject lớp là tập hợp của tên / giá trị cặp ( không có thứ tự ) nơi đậu là một lớp học với setter getter các phương thức cho các trường thành viên của nó. Chúng tôi có thể chuyển đổi một đối tượng JSON thành bean bằng cách sử dụng toBean () phương thức của JSONObject lớp học.

Cú pháp

public static Object toBean(JSONObject jsonObject, Class beanClass)

Ví dụ

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 +
                " ]";
      }
   }
}

Đầu ra

{
 "firstName": "Sai",
 "lastName": "Ram",
 "address": "Bangalore",
 "age": 30
}
Employee[ firstName = Sai, lastName = Ram, age = 30, address = Bangalore ]