Nikos Maravitsas

About Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

Gson Streaming to read and write JSON in Java example

In this example we are going to see GSON straming API to read and write JSON in a Java application. Streaming operation is the fastest and most efficient way to process JSON data. On the other hand it can be tricky to use, especially when reading from JSON represenation, because you have to handle all the data manually. You can take look ta the Jackson Streaming API to get the notion of streaming processing.
 
 
 
 
 
 

1. Write JSON to a File using JsonWriter

GsonStreamAPIExample.java:

package com.javacodegeeks.java.core;

import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.stream.JsonWriter;

public class GsonStreamAPIExample {

	private static final String jsonFilePath = "C:\\Users\\nikos7\\Desktop\\filesForExamples\\jsonFile.json";

	public static void main(String[] args) {

		try {

			FileWriter fileWriter = new FileWriter(jsonFilePath);

			JsonWriter jsonWriter = new JsonWriter(fileWriter);

			jsonWriter.beginObject(); 

			jsonWriter.name("domain").value("www.javacodegeeks.com");

			jsonWriter.name("members").value(200);

			jsonWriter.name("names");

			jsonWriter.beginArray();

			jsonWriter.value("Jack");

			jsonWriter.value("James");

			jsonWriter.value(3);

			jsonWriter.endArray();

			jsonWriter.endObject();

			jsonWriter.close();

			System.out.println("The file was created successfully!");

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

jsonFile.json:

{"domain":"www.javacodegeeks.com","members":200,"names":["Jack","James",3]}

1. Read JSON from File using JsonReader

This is the tricky part in the Streaming API. In this, every single string is considered a token. It’s a classic parsing procedure.

We are going to use jsonFile.json as an input file for the demp.

GsonStreamAPIExample.java:

package com.javacodegeeks.java.core;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import com.google.gson.stream.JsonReader;

public class GsonStreamAPIExample {

	private static final String jsonFilePath = "C:\\Users\\nikos7\\Desktop\\filesForExamples\\jsonFile.json";

	public static void main(String[] args) {

		try {

			FileReader fileReader = new FileReader(jsonFilePath);

			JsonReader jsonReader = new JsonReader(fileReader);

			jsonReader.beginObject();

			while (jsonReader.hasNext()) {

				String name = jsonReader.nextName();

				if (name.equals("domain")) {

					System.out.println("domain: "+jsonReader.nextString());

				} else if (name.equals("members")) {

					System.out.println("members: "+jsonReader.nextInt());

				} else if (name.equals("names")) {

					System.out.println("names: ");

					jsonReader.beginArray();

					while (jsonReader.hasNext()) {
						System.out.println(" "+jsonReader.nextString());
					}

					jsonReader.endArray();

				} else {
					// use this when you are not sure about all the contents in th JSON file
					jsonReader.skipValue();
				}
			}

			jsonReader.endObject();
			jsonReader.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

output:

domain: www.javacodegeeks.com
members: 200
names: 
 Jack
 James
 3

 
This was an example on how to use Gson Streaming API to read and write JSON in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close