Similar to Jackson Streaming API, Google GSON too provides streaming API for the situation where performance is utmost important. Gson Streaming API is based on Sequential read/write
and is very useful in situations where it is not desirable to load complete object model in memory(e.g complete data is not available). This is commonly known as token by token approach. You write as you read and your memory footprints remains low.
JsonWriter
& JsonReader
are core classes used for Streaming Write and Read in Streaming API.
- Spring MVC 4+Spring Security 4 + Hibernate Integration Example
- Spring MVC 4+AngularJS Routing with UI-Router Example
- Spring MVC 4+AngularJS Example
- Spring MVC 4 HelloWorld – Annotation/JavaConfig Example
- Spring MVC 4+Hibernate 4+MySQL+Maven integration example
- Spring 4 Hello World Example
- Spring Security 4 Hello World Annotation+XML Example
- Hibernate MySQL Maven Hello World Example (Annotation)
- TestNG Hello World Example
- JAXB2 Helloworld Example
- Spring Batch- Read a CSV file and write to an XML file
Step 1: Include GSON dependency in pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.websystique.json</groupId> <artifactId>GsonStreamingExample</artifactId> <version>1.0.0</version> <packaging>jar</packaging> <name>GsonStreamingExample</name> <dependencies> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.3.1</version> </dependency> </dependencies> </project>
Step 3: Write JSON using JsonWriter
Write the JSON content in a file. Basically in this approach, you build the JSON string structure from java object by yourself. You create the required opening/closing boundaries/brackets {}[]
for elements(objects/arrays) using JsonWriter beginObject/endObject
& beginArray/endArray
methods. And you set the actual elements using name
, their values using value
methods.
package com.websystique.json.gson; import java.io.FileReader; import java.io.FileWriter; import com.google.gson.stream.JsonWriter; public class GsonStreamingDemo { public static void main(String args[]) { JsonWriter writer; try { writer = new JsonWriter(new FileWriter("result.json")); writer.beginObject(); // { writer.name("name").value("AUDI"); // "name" : "AUDI" writer.name("model").value(2014); // "model" : 2014 writer.name("price").value(30000); // "price" : 30000 writer.name("colors"); // "colors" : writer.beginArray(); // [ writer.value("GRAY"); // "GRAY" writer.value("BLACK"); // "BLACK" writer.value("WHITE"); // "WHITE" writer.endArray(); // ] writer.endObject(); // } writer.close(); } catch (Exception e) { e.printStackTrace(); } } }
Following is the content of result.json
{"name":"AUDI","model":2014,"price":30000,"colors":["GRAY","BLACK","WHITE"]}
Step 4: Read JSON using JsonReader
Read the JSON content from a file. Basically you iterate over the input json string and read each token subsequently using JsonReader hasNext & nextName
methods. Depending on contract/element type, you get the actual element’s value using nextXXX()
.
As for writing, using JsonReader beginObject/endObject
& beginArray/endArray
methods to read opening/closing brackets.
We will use the output file generated from above.
package com.websystique.json.gson; import java.io.FileReader; import java.io.FileWriter; import com.google.gson.stream.JsonReader; public class GsonStreamingDemo { public static void main(String args[]) { JsonReader reader; try { reader = new JsonReader(new FileReader("result.json")); reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("name")) { System.out.println(reader.nextString()); } else if (name.equals("model")) { System.out.println(reader.nextInt()); } else if (name.equals("price")) { System.out.println(reader.nextDouble()); } else if (name.equals("colors")) { // it's an array. reader.beginArray(); while (reader.hasNext()) { System.out.println(reader.nextString()); } reader.endArray(); } else {// unexpected value, skip it or generate error reader.skipValue(); } } reader.endObject(); reader.close(); } catch (Exception e) { e.printStackTrace(); } } }
Following is the output from above main.
AUDI 2014 30000.0 GRAY BLACK WHITE
That’s it. In the next post we will learn about custom serialization using Google GSON serialization API.
References
If you like tutorials on this site, why not take a step further and connect me on Facebook , Google Plus & Twitter as well? I would love to hear your thoughts on these articles, it will help improve further our learning process.