Gson – Convert JSON to Java object example shows how to convert JSON to a Java object using the Gson library in Java.
How to convert JSON to Java object?
It is fairly easy to convert JSON to a Java object using the GSON library. We need to use the fromJson
method of the Gson class to convert JSON to a POJO class.
1 |
<T> T fromJson(String json, Class<T> classOfT) |
The fromJson
method converts the string JSON data to the given class object.
Here is a simple example to demonstrate that.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package com.javacodeexamples.gsonexamples; import com.google.gson.Gson; public class GsonJSONToJavaObjectExample { public static void main(String[] args) { //string containing employee data in JSON format String strJSON = "{\"id\":\"EMP001\", \"name\":\"Alex\"}"; /* * To convert JSON to Java object, use * the fromJson method of the Gson class */ Employee emp = new Gson().fromJson(strJSON, Employee.class); System.out.println("Id: " + emp.getId()); System.out.println("Name: " + emp.getName()); } } class Employee{ private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } |
Output
1 2 |
Id: EMP001 Name: Alex |
We can also read a JSON from a file and convert it to a Java object as given below. Here is the employee.json file content that we are going to read and convert to an Employee object.
1 |
{"id":"EMP001", "name":"Alex"} |
1 2 3 4 5 6 7 8 9 10 |
try (BufferedReader reader = new BufferedReader(new FileReader("D:\\employee.json"))) { Employee emp = new Gson().fromJson(reader, Employee.class); System.out.println("Id: " + emp.getId()); System.out.println("Name: " + emp.getName()); }catch(Exception e) { e.printStackTrace(); } |
Output
1 2 |
Id: EMP001 Name: Alex |
We can also read JSON from a URL and convert it to a Java object as given below.
1 2 3 4 5 6 7 8 9 10 11 12 |
URL url = new URL("http://www.example.com/apiurl"); try (InputStreamReader reader = new InputStreamReader(url.openStream())) { Employee emp = new Gson().fromJson(reader, Employee.class); System.out.println("Id: " + emp.getId()); System.out.println("Name: " + emp.getName()); }catch(Exception e) { e.printStackTrace(); } |
Please let me know your views in the comments section below.