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.

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
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.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books