首页 > 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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板