Java Gson Read JSON File using JsonReader

Tags: JSON gson Gson JsonReader JsonReader beginObject JsonReader endObject JsonReader nextName JsonReader nextString FileReader

In this Java Gson tutorial we learn how to use the com.google.gson.stream.JsonReader class of Gson library to read JSON file content.

How to add Gson to the Java project

To use the Gson library in the Gradle build project, add the following dependency into the build.gradle file.

implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.7'

To use the Gson library in the Maven build project, add the following dependency into the pom.xml file.

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

Or you can download the Gson jar file from Maven Central at gson-2.8.7.jar

To have more information about the Gson library you can visit the project repository at github.com/google/gson

What is the JsonReader class?

The com.google.gson.stream.JsonReader is a class of Gson library to allow reading JSON content as a stream of tokens.

How to read JSON file using JsonReader

For example, we have a JSON File as below

D:\Data\test.json

{"firstName":"Simple","lastName":"Solution","email":"contact@simplesolution.dev","website":"https://simplesolution.dev"}

In the following Java program we show you how to read the above JSON file using the JsonReader class.

JsonReaderExample.java

import com.google.gson.stream.JsonReader;

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

public class JsonReaderExample {
    public static void main(String... args) {
        try(FileReader fileReader = new FileReader("D:\\Data\\test.json");
            JsonReader jsonReader = new JsonReader(fileReader)) {
            jsonReader.beginObject();
            while (jsonReader.hasNext()) {
                String name = jsonReader.nextName();
                String value = jsonReader.nextString();

                System.out.println("Name: " + name);
                System.out.println("Value: " + value + "\n");
            }
            jsonReader.endObject();

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

    }
}
The output is:
Name: firstName
Value: Simple

Name: lastName
Value: Solution

Name: email
Value: contact@simplesolution.dev

Name: website
Value: https://simplesolution.dev

Happy Coding 😊