Generating the JSON representation from the object model

Gson has simplified APIs to convert the object model into the JSON content. Depending upon the type of the object model, you can use either of the following APIs to get the JSON representation:

  • To convert a Java object into JSON, you can call the toJson(Object src) method. Here is an example:
// Get Employee object that needs  
//to be converted into JSON
Employee emp=getEmployee();
Gson gson = new Gson();
// create JSON String from Object
String jsonEmp = gson.toJson(emp);
  • To convert a parameterized collection into a JSON string, you can use toJson(Object src, Type typeOfSrc). Here is an example:
//Get Employee list that needs to be converted into JSON 
List<Employee> employees= getEmployeeList();
Gson gson = new Gson();
//Specify collection type that you want
//to convert into JSON
Type typeOfSource = new
TypeToken<List<Employee>>(){}.getType();
// create JSON String from Object
String jsonEmps = gson.toJson(employees, typeOfSource);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.179.59