Gson – JsonReader

Learn to work with Gson JsonReader class which is a pull based streaming JSON parser. It helps in reading a JSON as a stream of tokens.

1. JsonReader

  • The JsonReader is the streaming JSON parser and an example of pull parser. A push parser parses through the JSON tokens and pushes them into an event handler.
  • It helps in reading a JSON (RFC 7159) encoded value as a stream of tokens.
  • It reads both literal values (strings, numbers, booleans, and nulls) as well as the begin and end delimiters of objects and arrays.
  • The tokens are traversed in depth-first order, the same order that they appear in the JSON document.

Read More : Streaming parser of XML

2. Tokens

In streaming mode, every JSON data is considered an individual token. When we use JsonReader to process it, each token will be processed sequentially. For example,

{
	"name":"Lokesh"
}

While parsing with JsonReader, above JSON will generate 4 tokens:

  • Token 1 = {
  • Token 2 = name
  • Token 3 = Lokesh
  • Token 4 = }

3. How to create GSON JsonReader

We can create a JsonReader instance using it’s simple constructor which accepts java.io.Reader type input stream.

String json = "{}";
JsonReader jsonReader = new JsonReader( new StringReader(json) );

We can use one of following readers based on source of JSON stream:

  • BufferedReader
  • LineNumberReader
  • CharArrayReader
  • InputStreamReader
  • FileReader
  • FilterReader
  • PushbackReader
  • PipedReader
  • StringReader

4. Read JSON Stream

After creating JsonReader wrapping a valid JSON source, we can start iterating over stream tokens and look into token values.

Following is an example to read a simple JSON using JsonReader in form on tokens.

import java.io.IOException;
import java.io.StringReader;

import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;

public class Main 
{
	public static void main(String[] args) throws Exception 
	{

		String json = "{'id': 1001,'firstName': 'Lokesh','lastName': 'Gupta','email': null}";

		JsonReader jsonReader = new JsonReader(new StringReader(json));
		jsonReader.setLenient(true);
		
		try 
		{
			while (jsonReader.hasNext()) 
			{
				JsonToken nextToken = jsonReader.peek();
				
				if (JsonToken.BEGIN_OBJECT.equals(nextToken)) {

					jsonReader.beginObject();

				} else if (JsonToken.NAME.equals(nextToken)) {

					String name = jsonReader.nextName();
					System.out.println("Token KEY >>>> " + name);

				} else if (JsonToken.STRING.equals(nextToken)) {

					String value = jsonReader.nextString();
					System.out.println("Token Value >>>> " + value);

				} else if (JsonToken.NUMBER.equals(nextToken)) {

					long value = jsonReader.nextLong();
					System.out.println("Token Value >>>> " + value);

				} else if (JsonToken.NULL.equals(nextToken)) {

					jsonReader.nextNull();
					System.out.println("Token Value >>>> null");
					
				} else if (JsonToken.END_OBJECT.equals(nextToken)) {

					jsonReader.endObject();

				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			jsonReader.close();
		}
	}
}
Token KEY >>>> id
Token Value >>>> 1001

Token KEY >>>> firstName
Token Value >>>> Lokesh

Token KEY >>>> lastName
Token Value >>>> Gupta

Token KEY >>>> email
Token Value >>>> null

In above example:

  • The hasNext() method of the JsonReader returns true if it has more tokens.
  • The peek() method returns the next JSON token, but without moving over it.
  • Multiple calls to peek() subsequently will return the same JSON token.
  • The type of return token can be checked with constants of JsonToken class.
  • Array’s opening and closing brackets '[' and ']' are checked with beginArray() and endArray() methods.
  • Object’s opening and closing brackets '{' and '}' are checked with beginObject() and endObject() methods.
  • The key of the token is of type JsonToken.NAME. Use nextName() method to get the key name.

  • After determining the type of token, get the value of token using method like nextLong(), nextString(), nextInt() etc.
  • Null literals can be consumed using either nextNull() or skipValue().
  • All next....() method return the value of the current token and moves the internal pointer to the next.
  • When an unknown name is encountered, strict parsers should fail with an exception. Lenient parsers should call skipValue() to recursively skip the value’s nested tokens, which may otherwise conflict.

Drop me your questions related to Gson JsonReader.

Happy Learning !!

Reference:

Gson User Guide
JsonReader Java Doc

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial