How to deserialize a JSON into an existing object in Java?

JavaJSONObject Oriented ProgrammingProgramming

The Flexjson is a lightweight java library for serializing and deserializing java beans, maps, arrays, and collections in JSON format. We can also deserialize a JSON string to an existing object using the deserializeInto() method of JSONDeserializer class, this method deserializes the given input into the existing object target. The values in the json input can overwrite values in the target object. This means if a value is included in JSON a new object can be created and set into the existing object.

Syntax

public T deserializeInto(String input, T target)

Example

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 +
      " ]";
   }
}

Output

Employee[ firstName = Adithya, lastName = Ram, age = 25, salary = 35000.0 ]
Employee[ firstName = Adithya, lastName = Ram, age = 30, salary = 45000.0 ]
raja
Published on 01-Oct-2019 15:38:29
Advertisements