Posted In: GSON, JSON

How to use GSON streaming JsonReader to read big JSON file

Usecase – You have JSON data stored at a location. It is big so do not have luxury to read it fully in GSON or you just need use some part of JSON. GSON API provides streaming JsonReader class to do that.

Maven Jackson 2X

<dependency>
	<groupId>com.google.code.gson</groupId>
	<artifactId>gson</artifactId>
	<version>2.8.0</version>
</dependency>

Classes used from GSON

com.google.gson.stream.JsonReader

Test data

[
  {
    "albumId": 100,
    "id": 4999,
    "title": "in voluptate sit officia non nesciunt quis",
    "url": "http://placehold.it/600/1b9d08",
    "thumbnailUrl": "http://placehold.it/150/1b9d08"
  },
  {
    "albumId": 100,
    "id": 5000,
    "title": "error quasi sunt cupiditate voluptate ea odit beatae",
    "url": "http://placehold.it/600/6dd9cb",
    "thumbnailUrl": "http://placehold.it/150/6dd9cb"
  }
]
package com.example.testing.json;

import java.io.FileReader;

import com.google.gson.stream.JsonReader;

public class GsonReadJson {

	public static void main(String[] args) {
		new GsonReadJson().proceed();
	}

	public void proceed() {
		try {
			JsonReader reader = new JsonReader(new FileReader("e:\\abhijit\\javausecase\\bigjson.json"));
			reader.beginArray();
			while (reader.hasNext()) {
				System.out.println("\n");
				reader.beginObject();
				System.out.println(reader.nextName() + " : " + reader.nextInt());
				System.out.println(reader.nextName() + " : " + reader.nextString());
				System.out.println(reader.nextName() + " : " + reader.nextString());
				System.out.println(reader.nextName() + " : " + reader.nextString());
				System.out.println(reader.nextName() + " : " + reader.nextString());
				reader.endObject();
			}
			reader.endArray();
			reader.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output

albumId : 100
id : 4999
title : in voluptate sit officia non nesciunt quis
url : http://placehold.it/600/1b9d08
thumbnailUrl : http://placehold.it/150/1b9d08


albumId : 100
id : 5000
title : error quasi sunt cupiditate voluptate ea odit beatae
url : http://placehold.it/600/6dd9cb
thumbnailUrl : http://placehold.it/150/6dd9cb

Tags:

by , on August 8th, 2017

  • Categories