Parse JSON using Gson, convert JSON to Object and vice-versa
To parse JSON using Gson, you need to download gson-2.8.5.jar from gson-2.8.5.jar
For converting small- or medium-sized lists, Gson provides a better response compared to Jackson. For large lists, Jackson provides a better response than Gson.
Below is the JSON string to parse
{ "id":12345, "name":"Jason Bourne", "age":35, "emailaddress":["j.bourne@gmail.com", "j.bourne@yahoo.com"] }
Java class used to convert JSON String to object and vice-versa.
import java.util.List; public class Employee { private int id; private String name; private int age; private List<String> emailaddress; // removed getter and setter @Override public String toString() { return "Employee [id=" + id + ", name=" + name + "," +" age=" + age + ", emailaddress=" + emailaddress + "]"; } }
1) Convert JSON string to Java object using Gson.
import java.util.ArrayList; import java.util.List; import com.google.gson.Gson; public class TestGsonParser { public static void main(String[] args) { String jsonString = "{\"id\":12345, \"name\":\"Jason Bourne\", \"age\":35," + " \"emailaddress\":[\"j.bourne@gmail.com\", \"j.bourne@yahoo.com\"]}"; Gson gson = new Gson(); // parse json string to object Employee employee = gson.fromJson(jsonString, Employee.class); System.out.println(employee); } }
Output :
Employee [id=12345, name=Jason Bourne, age=35, emailaddress=[j.bourne@gmail.com, j.bourne@yahoo.com]]
2) Convert Java object to JSON string using Gson.
import java.util.ArrayList; import java.util.List; import com.google.gson.Gson; public class TestGsonParser { public static void main(String[] args) { Employee emp = new Employee(); emp.setId(2345); emp.setName("James Bond"); emp.setAge(40); List<String> emailaddress = new ArrayList<>(); emailaddress.add("jbond@yahoo.com"); emailaddress.add("jbond@gmail.com"); emp.setEmailaddress(emailaddress); Gson gson = new Gson(); String jsonEmp = gson.toJson(emp); // create JSON String from Object System.out.print(jsonEmp); } }
Output :
{"id":2345,"name":"James Bond","age":40,"emailaddress":["jbond@yahoo.com","jbond@gmail.com"]}
You can prettify above JSON
import java.util.ArrayList; import java.util.List; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class TestGsonParser { public static void main(String[] args) { Employee emp = new Employee(); emp.setId(2345); emp.setName("James Bond"); emp.setAge(40); List<String> emailaddress = new ArrayList<>(); emailaddress.add("jbond@yahoo.com"); emailaddress.add("jbond@gmail.com"); emp.setEmailaddress(emailaddress); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String jsonEmp = gson.toJson(emp); // create JSON String from Object System.out.print(jsonEmp); } }
Output :
{ "id": 2345, "name": "James Bond", "age": 40, "emailaddress": [ "jbond@yahoo.com", "jbond@gmail.com" ] }