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: GSON JSON Streaming API Example
- Apache (13)
- Build Tools (2)
- Gradle (2)
- Caching (1)
- cpanel (1)
- cURL (1)
- Database (7)
- Hibernate (5)
- Java Core (38)
- Java Script (15)
- Bootstrap (1)
- File Upload (7)
- jQuery (3)
- React (3)
- JEE (13)
- JSON (41)
- GSON (13)
- Jackson 1X (1)
- Jackson 2X (12)
- jsoniter (1)
- Logging (2)
- Apache Commons Logging (1)
- Apache Log4J (1)
- Logback (1)
- SLF4J (1)
- MongoDB (1)
- OS (1)
- Linux (1)
- Security (5)
- Server (4)
- Tomcat (4)
- Service (2)
- Micro (2)
- Spring (46)
- Pattern (2)
- Spring Boot (20)
- Spring Data (4)
- Spring MVC (8)
- Spring REST (13)
- Spring Security (7)
- Testing (11)
- XML (5)
- JDOM XML Parser (1)