Gson is a java json library created by Google that can be used to generate JSON. By using Gson we can generate JSON and convert JSON to java object. We can call the fromJson() method of the Gson class to convert the JSON object into a Java object.
public <T> fromJson(java.lang.String json, java.lang.Class<T> classOfT) throws JsonSyntaxException
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<strong> </strong>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; } }
raja 25
The above is the detailed content of Convert JSON object to Java object using Gson library in Java?. For more information, please follow other related articles on the PHP Chinese website!