如何将 JSON 反序列化到 Java 中的现有对象?
Flexjson 是一个轻量级java库,用于以 JSON 格式序列化和反序列化 java bean、map、array 和集合。我们还可以使用JSONDeserializer 类的deserializeInto() 方法将JSON 字符串反序列化为现有对象,此方法将给定的输入反序列化为现有对象 target。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 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP