如何在 Java 中将 JSON 反序列化为现有对象?
javajsonobject oriented programmingprogramming
Flexjson 是一个 轻量级 Java 库,用于 序列化 和 反序列化 JSON 格式的 Java bean、映射、数组和集合。我们还可以使用 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); } } // Employee class 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 ]