首頁 >Java >java教程 >如何使用Java中的JSON-lib API將JSON字串轉換為Bean?

如何使用Java中的JSON-lib API將JSON字串轉換為Bean?

王林
王林轉載
2023-09-17 20:33:06874瀏覽

如何使用Java中的JSON-lib API将JSON字符串转换为Bean?

JSON-lib#API是一個 Java 函式庫,用於以 JSON 格式序列化和反序列化 java bean、映射、陣列集合。我們需要將 JSON 字串轉換為 bean,方法是先將字串轉換為 JSON 對象,然後將其轉換為 java bean。

語法

public static Object toBean(JSONObject jsonObject, Class beanClass)

在下面的程式中,我們可以將 JSON 字串轉換為 bean。

範例

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
public class ConvertJSONStringToBeanTest {
   public static void main(String[] args) {
      String jsonStr = "{\"firstName\": \"Adithya\", \"lastName\": \"Sai\", \"age\": 30, \"technology\": \"Java\"}";
      JSONObject jsonObj = (JSONObject)JSONSerializer.toJSON(jsonStr); // convert String to JSON
      System.out.println(jsonObj);
     
      Student student = (Student)JSONObject.toBean(jsonObj, Student.class); // convert JSON to Bean
      System.out.println(student.toString());
   }
   public static class Student {
      private String firstName;
      private String lastName;
      private int age;
      private String technology;
      public Student() {
      }
      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 getTechnology () {
         return technology;
      }
      public void setTechnology(String technology) {
         this.technology = technology;
     }
      public String toString() {
         return "Student[ " +
         "firstName = " + firstName +
         ", lastName = " + lastName +
         ", age = " + age +
         ", technology = " + technology +
         " ]";
      }
   }
}

輸出

{"firstName":"Adithya","lastName":"Sai","age":30,"technology":"Java"}
Student[ firstName = Adithya, lastName = Sai, age = 30, technology = Java ]

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

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除