Generating the object model from the JSON representation

Gson offers simpler APIs to convert the JSON representation into Java objects. To do this, you can call the fromJson(Reader json, Class<T> classOfT) method on the com.google.gson.Gson object. The following example will help you understand the end-to-end use of Gson APIs for deserializing the JSON content to Java objects:

  1. The first step is to create a Gson instance. The Gson class offers all the necessary methods for serializing and deserializing JSON data. You can simply create an instance by calling new Gson(). However, in this example, we use com.google.gson.GsonBuilder to create a Gson instance. This is because GsonBuilder lets you override the default configuration for a Gson instance. We use this feature to override the default date format used for serializing and deserializing the date fields present in the JSON content. The following code snippet creates a Gson instance:
//Other imports are removed for brevity 
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

// Get GsonBuilder object
GsonBuilder gsonBuilder = new GsonBuilder();
//Set date format for converting date presented in
//form (in JSON data) to java.util.Date
gsonBuilder.setDateFormat("yyyy-MM-dd");
//Get gson object
Gson gson = gsonBuilder.create();
  1. The next step is to convert the JSON content into an appropriate Java class. You can do this by invoking fromJson(Reader json, Class<T> classOfT) on the Gson instance. The following sample code converts the JSON representation of the employee object into the employee Java object:
//Read the json input file with current class's class  
//loader
// emp.json contains JSON employee objectInputStream inputStream =
getClass().getResourceAsStream("/emp.json");
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
//Converts JSON string to Employee object
Employee employee = gson.fromJson(reader, Employee.class);
..................Content has been hidden....................

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