Categories: Json

Gson Streaming Api Example

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.


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

Share
Published by

Recent Posts

Spring Boot + AngularJS + Spring Data + JPA CRUD App Example

In this post we will be developing a full-blown CRUD application using Spring Boot, AngularJS, Spring Data, JPA/Hibernate and MySQL,…

7 years ago

Spring Boot Rest API Example

Spring Boot complements Spring REST support by providing default dependencies/converters out of the box. Writing RESTful services in Spring Boot…

7 years ago

Spring Boot WAR deployment example

Being able to start the application as standalone jar is great, but sometimes it might not be possible to run…

7 years ago

Spring Boot Introduction + hello world example

Spring framework has taken the software development industry by storm. Dependency Injection, rock solid MVC framework, Transaction management, messaging support,…

7 years ago

Secure Spring REST API using OAuth2

Let's secure our Spring REST API using OAuth2 this time, a simple guide showing what is required to secure a…

8 years ago

AngularJS+Spring Security using Basic Authentication

This post shows how an AngularJS application can consume a REST API which is secured with Basic authentication using Spring…

8 years ago