Convert JSON object to Java object using Gson library in Java?

JavaJSONObject Oriented ProgrammingProgramming

A Gson is a json library for java, which is created by Google and it can be used to generate a JSON. By using Gson, we can generate JSON and convert JSON to java objects. We can call the fromJson() method of Gson class to convert a JSON object to Java Object.

Syntax

public <T> fromJson(java.lang.String json, java.lang.Class<T> classOfT) throws JsonSyntaxException

Example

import com.google.gson.*;
public class JSONtoJavaObjTest {
   public static void main(String[] args) {
      Gson gson = new Gson();
      Emp emp = gson.fromJson("{'name':'raja','age':25}", Emp.class);
      System.out.println(emp.getName());
      System.out.println(emp.getAge());
   }
}
// Emp class
class Emp {
   String name;
   int age;
   public Emp() {
      super();
   }
   public Emp(String name, int age) {
      super();
      this.name = name;
      this.age = age;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public int getAge() {
      return age;
   }
   
   public void setAge(int age) {
      this.age = age;
   }
}

Output

raja
25
raja
Published on 20-Sep-2019 11:28:22
Advertisements