如何在Java中将JSON反序列化为现有对象?

Flexjson 是一个轻量级 的Java库序列化反序列化 的Java bean,映射,数组和集合JSON格式。我们还可以使用JSONDeserializer类的deserializeInto  () 方法将JSON字符串反序列化为现有对象 ,此方法将给定的输入反序列化为现有对象目标。json输入中的值可以覆盖目标对象中的值。这意味着,如果JSON中包含值,则可以创建一个新对象并将其设置到现有对象中。

语法

public T deserializeInto(String input, T target)

示例

import flexjson.JSONDeserializer;
public class JsonDeserializeTest {
   public static void main(String[] args) {
      Employee emp = new Employee("Adithya", "Ram", 25, 35000.00);
      System.out.println(emp);
      JSONDeserializer<Employee> deserializer = new JSONDeserializer<Employee>();
      String jsonStr =
                     "{" +
                     "\"age\": 30," +
                     "\"salary\": 45000.00" +
                     "}";
      emp = deserializer.deserializeInto(jsonStr, emp);
      System.out.println(emp);
   }
}
//员工阶层
class Employee {
   private String firstName;
   private String lastName;
   private int age;
   private double salary;
   public Employee() {}
   public Employee(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 "Employee[ " +
      "firstName = " + firstName +
      ", lastName = " + lastName +
      ", age = " + age +
      ", salary = " + salary +
      " ]";
   }
}

输出结果

Employee[ firstName = Adithya, lastName = Ram, age = 25, salary = 35000.0 ]
Employee[ firstName = Adithya, lastName = Ram, age = 30, salary = 45000.0 ]