Reading JSON data with Gson streaming APIs

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.json file into a list of Employee objects. The steps are as follows:

  1. 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 InputStreamReader instance as input.
  2. 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;
}
..................Content has been hidden....................

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