Generating the parameterized Java collection from the JSON representation

The previous example demonstrated the Gson APIs for converting a JSON representation of a single employee object into a Java object. This section discusses how to convert a JSON object array into a Java collection. You can do this by calling the fromJson(JsonReader reader, Type typeOfT) method on the Gson instance. Let's take an example to better understand this API. The steps are as follows:

  1. The emp-array.json file used in this example contains a JSON array of the employee objects.
  2. This example converts the JSON array read from the input file into the List<Employee> collection object, which is a parameterized collection type (generic type). We use com.google.gson.reflect.TypeToken<T> to define the collection type that holds the Employee objects.
  3. To deserialize the JSON data read from the file into the List<Employee> object, call fromJson(Reader json, Type typeOfT) on the Gson object with the file input stream reader and the desired TypeToken object as the parameter.

The following code snippet illustrates these steps:

//Step 1: Read emp-array.json  
InputStream inputStream =
getClass().getResourceAsStream(("/emp-array.json");
BufferedReader reader = new BufferedReader(new
InputStreamReader(inputStream));
// Step 2: Define TypeToken
// Define a parameterized collection type to hold the List
// of Employees returned by Gson::fromJSon method call.
Type listType = new TypeToken<ArrayList<Employee>>(){}
.getType();
//Step 3: Convert JSON array to List<Employee>
//Generates list of employees by calling Gson::fromJson()
Gson gson = new Gson();
List<Employee> employees = gson.fromJson(reader, listType);
How does Gson map a JSON object to a Java class?

The default mapping mechanism used by Gson is based on bean properties. The binding layer copies the matching properties from the source to the destination. This implies that all the names present in a JSON object need to match the Java class properties for the default mapping mechanism to work. However, you can override the default mapping behavior by annotating the desired attribute with @SerializedName. This annotation indicates that the annotated member should be serialized to JSON with the provided name value as its field name.
..................Content has been hidden....................

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