如何使用 Java 中的 flexjson 将 JSON 反序列化为 Java 对象?
javajsonobject oriented programmingprogramming
Flexjson 是一个 轻量级 库,用于将 Java 对象序列化 和 反序列化 为 JSON 格式,允许对象的深层和浅层复制。为了使用 flexjon 运行 Java 程序,我们需要导入 flexjson 包。我们可以使用 JSONDeserializer 类的 deserialize() 方法将 JSON 反序列化为 Java 对象,它以 json 字符串作为输入,并从该 json 表示生成静态类型对象图。默认情况下,它使用 json 数据中的 class 属性将无类型的通用 json 数据映射到特定的 Java 类型。
语法
public T deserialize(String input)
在下面的程序中,将 JSON 反序列化为 Java 对象
示例
import flexjson.*; public class DeserializeJSONTest { public static void main(String[] args) { JSONDeserializer<Student> deserializer = new JSONDeserializer<Student>(); String jsonStr = "{" + "\"firstName\": \"Ravi\"," + "\"lastName\": \"Chandra\"," + "\"age\": 35," + "\"class\": \"Student\"," + "\"salary\": 50000.00," + "}"; Student student = deserializer.deserialize(jsonStr); System.out.println(student); } } // Student classclass Student { private String firstName; private String lastName; private int age; private double salary; public Student() {} public Student(String firstName, String lastName, int age, double salary) { super(); this.firstName = firstName; this.lastName = lastName; this.age = age; this.salary = salary; } 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 double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public String toString() { return "Student[ " + "firstName = " + firstName + ", lastName = " + lastName + ", age = " + age + ", salary = " + salary + " ]"; } }
输出
Student[ firstName = Ravi, lastName = Chandra, age = 35, salary = 50000.0 ]