如何使用flexjson在Java中从Reader流反序列化Java对象?

如何使用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对象?的详细内容,更多请关注其它相关文章!