Home  >  Article  >  Java  >  How to convert JSON object to bean using JSON-lib API in Java?

How to convert JSON object to bean using JSON-lib API in Java?

WBOY
WBOYforward
2023-09-05 10:33:021213browse

如何使用Java中的JSON-lib API将JSON对象转换为bean?

The JSONObject class is a collection containing name/value pairs (unordered), where a bean is a member with The class for the setter and getter methods of the field. We can convert a JSON object into a bean using the toBean() method of the JSONObject class.

Syntax

public static Object toBean(JSONObject jsonObject, Class beanClass)

Example

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, <strong>Employee.class</strong>);
      System.out.println(emp.toString());
   }
<strong>   </strong>// 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 +
                " ]";
      }
   }
}

Output

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

The above is the detailed content of How to convert JSON object to bean using JSON-lib API in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete