How to deserialize a JSON to Java object using the flexjson in Java?

JavaJSONObject Oriented ProgrammingProgramming

The Flexjson is a lightweight library for serializing and deserializing Java objects into and from JSON format allowing both deep and shallow copies of objects. In order to run a Java program with flexjon, we need to import a flexjson package. We can deserialize a JSON to Java object using the deserialize() method of JSONDeserializer class, it takes as input a json string and produces a static typed object graph from that json representation. By default, it uses the class property in the json data in order to map the untyped generic json data into a specific Java type.

Syntax

public T deserialize(String input)

In the below program, deserialize a JSON to Java object

Example

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

Output

Student[ firstName = Ravi, lastName = Chandra, age = 35, salary = 50000.0 ]
raja
Published on 27-Sep-2019 11:08:11
Advertisements