首頁 > Java > java教程 > 如何使用flexjson在Java中從Reader流反序列化Java物件?

如何使用flexjson在Java中從Reader流反序列化Java物件?

王林
發布: 2023-09-10 22:57:04
轉載
1050 人瀏覽過

如何使用flexjson在Java中從Reader流反序列化Java物件?

Flexjson是一個輕量級函式庫,用於將Java 物件序列化為JSON 格式以及反序列化為JSON 格式。我們可以使用 JSONDeserializer 類別的 deserialize() 方法從 Reader 流中反序列化 Java 對象,它使用 Reader 類別的實例作為 JSON輸入。

語法

public T deserialize(Reader input)
登入後複製

範例

import java.io.*;
import flexjson.JSONDeserializer;
public class JSONDeserializeReaderTest {
   public static void main(String[] args) {
      JSONDeserializer<Student> deserializer = new JSONDeserializer<Student>();
      String jsonStr =
                       "{" +
                        "\"firstName\": \"Adithya\"," +
                        "\"lastName\": \"Sai\"," +
                        "\"age\": 25," +
                        "\"address\": \"Hyderabad\"" +
                        "\"class\": \"Student\"" +
                       "}";
      Student student = deserializer.deserialize(new StringReader(jsonStr));
      System.out.println(student);
   }
}
// Student class
class Student {
   private String firstName;
   private String lastName;
   private int age;
   private String address;
   public Student() {}
   public Student(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 "Student[ " +
      "firstName = " + firstName +
      ", lastName = " + lastName +
      ", age = " + age +
      ", address = " + address +
      " ]";
   }
}
登入後複製

輸出

Student[ firstName = Adithya, lastName = Sai, age = 25, address = Hyderabad ]
登入後複製

以上是如何使用flexjson在Java中從Reader流反序列化Java物件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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