Gson is an open source Java library that can be used for converting Java objects into JSON representations and vice versa. The Gson library was originally developed by Google for its internal use and later open sourced under the terms of Apache License 2.0.
To learn the dependencies of Gson APIs, refer to
https://github.com/google/gson/blob/master/UserGuide.md#TOC-Gson-With-Maven.
The main class in the Gson library that you will use for building an object model from the JSON data is the com.google.gson.Gson class. Here is a list of the core Gson classes from the object model API category:
Class | Description |
com.google.gson.GsonBuilder | This class is useful when you need to construct a Gson instance, overriding the default configurations such as custom date format, pretty printing, and custom serialization. |
com.google.gson.Gson | This class is the main class for using Gson. This class does conversions from JSON to Java objects and the other way round. |
com.google.gson.reflect.TypeToken<T> | This class is used for getting a generic type for a class. The resulting type can be used for serializing and deserializing JSON data. |
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:
- 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();
- 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 employeeJava 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);
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:
- The emp-array.json file used in this example contains a JSON array of the employee objects.
- 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.
- 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.
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);
In addition to the object model APIs, the Gson library supports the streaming APIs for reading and writing the JSON representations. The streaming APIs in Gson follow the pull parser model. Here is a list of the important streaming API classes in Gson:
Class | Description |
com.google.gson.stream.JsonReader | This class reads the JSON-encoded value as a stream of tokens. Tokens are read in the same order as they appear in the JSON document. |
com.google.gson.stream.JsonWriter | This class writes a JSON-encoded value to the stream, one token at a time. |
| The following example demonstrates the use of the Gson streaming APIs for reading JSON data.
This example converts the JSON array of employee objects present in the emp-array.jsonfile into a list of Employee objects. The steps are as follows: Gson provides com.google.gson.stream.JsonReader to read the JSON encoded value as a stream of tokens. You can create a JsonReader instance by supplying the InputStreamReaderinstance as input. As the next step, start parsing the contents. The tokens returned by JsonReader are traversed in the same order as they appear in the JSON document. As this example uses an array of JSON objects as input, the parser starts off by calling beginArray(). This call consumes the array's opening bracket. The client then calls beginObject() to consume the object's opening brace. This call is followed by a series of nextName() and next<DataType>, such as nextString(), to read the name value representing the object. After reading the entire object, the client calls endObject() to consume the next token from the JSON stream and asserts that it is the end of the current object. Once all the objects are read, the client invokes endArray() to consume the next token from the JSON stream and asserts that it is the end of the current array.
The following code snippet implements the two preceding steps: //Step 1: Read emp-array.json file containing JSON // array of employees InputStream inputStream = getClass().getResourceAsStream("/emp-array.json"); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); //Step 2: Start parsing the contents List<Employee> employeeList = new ArrayList<Employee>(); JsonReader reader = new JsonReader(inputStreamReader); reader.beginArray(); while (reader.hasNext()) { // The method readEmployee(...) is listed below Employee employee = readEmployee(reader); employeeList.add(employee); } reader.endArray(); reader.close(); Here is the definition of the readEmployee(JsonReader reader) method used in the preceding code snippet: // This method is referred in the above code snippet to create // Employee object private Employee readEmployee(JsonReader reader) throws IOException { Employee employee = new Employee(); reader.beginObject(); while (reader.hasNext()) { String keyName = reader.nextName(); switch (keyName) { case "firstName": employee.setFirstName(reader.nextString()); break; case "lastName": employee.setLastName(reader.nextString()); break; case "email": employee.setEmail(reader.nextString()); break; case "employeeId": employee.setEmployeeId(reader.nextInt()); break; default: } } reader.endObject(); return employee; } You can use com.google.gson.stream.JsonWriter to write the JSON-encoded value to the stream. The following example demonstrates the use of Gson streaming APIs for writing JSON data. This example writes the JSON array representation of employeeobjects to the emp-array.json file. The steps are as follows: - To write the JSON content, build the JsonWriter object, which takes the implementation of java.io.Writer as the input.
- Once the JsonWriter instance is created, start writing the JSON content. As this example writes an array of the employee objects, we start by invoking the beginArray() method. This call begins encoding a new array. Then, call beginObject() to start encoding a new object. This is followed by the encoding of the name and the value. To finish the encoding of the current object, call endObject(), and to finish the encoding of the current array, call endArray():
//Step 1: Build JsonWriter to read the JSON contents OutputStream outputStream = new FileOutputStream( "emp-array.json"); BufferedWriter bufferedWriter= new BufferedWriter( new OutputStreamWriter(outputStream)); //Creates JsonWriter object JsonWriter writer = new JsonWriter(bufferedWriter); //Step 2: Start writing JSON contents //Starts with writing array writer.beginArray(); List<Employee> employees = getEmployeesList(); for (Employee employee : employees) { //start encoding the object writer.beginObject(); //Write name:value pair to the object writer.name("employeeId").value (employee.getEmployeeId()); writer.name("firstName").value(employee.getFirstName()); writer.name("lastName").value(employee.getLastName()); writer.name("email").value(employee.getEmail()); //Finish encoding of the object writer.endObject(); } //Finish encoding of the array writer.endArray(); writer.flush(); //close writer writer.close(); With this, we have finished our discussion on the three popular JSON processing frameworks that you may find today. We may revisit some of these tools and frameworks with more complex use cases later in the book. In the following section, let's explore the proposed enhancements in Java EE8 for processing JSON.
|
|
|
Comments
Post a Comment