首頁 > Java > java教程 > 如何使用Java中的JSON-lib API將JSON物件轉換為bean?

如何使用Java中的JSON-lib API將JSON物件轉換為bean?

WBOY
發布: 2023-09-05 10:33:02
轉載
1276 人瀏覽過

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

JSONObject類別是一個包含名稱/值對(無序)的集合,其中bean是一個具有其成員字段的settergetter方法的類別。我們可以使用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, <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 +
                " ]";
      }
   }
}
登入後複製

輸出

{
 "firstName": "Sai",
 "lastName": "Ram",
 "address": "Bangalore",
 "age": 30
}
Employee[ firstName = Sai, lastName = Ram, age = 30, address = Bangalore ]
登入後複製

以上是如何使用Java中的JSON-lib API將JSON物件轉換為bean?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板