Read json content from a file using GSON in Java

Published by admin on

Java read json from a file using GSON

Read JSON content from a file using GSON in Java :

This tutorial will show you how to read JSON content from a file in Java using the GSON library.
Gson is an opensource library developed by Google. It can convert a Java object to JSON and also it can convert back JSON content to its equivalent Java object.

Importing GSON :

As I have mentioned earlier that gson is an opensource project and the source code is available on Github here.
You can easily import it to a maven or gradle project.
Use the below dependency for a gradle project :

dependencies {
  implementation 'com.google.code.gson:gson:2.8.5'
}

And, use below for a maven project :

  com.google.code.gson
  gson
  2.8.5

You can also download the jar file from here and include it in your project from here.

Make sure to use the updated version of the library.

Create one JSON file :

First of all, create one example.json file and add the below JSON content :

[
  {
    "_id": "5c076be16f76894c3ffc838b",
    "index": 0,
    "friends": [
      {
        "id": 0,
        "name": "Clayton Perry"
      },
      {
        "id": 1,
        "name": "Willa Moore"
      }
    ]
  },
  {
    "_id": "5c076be1a83a0d7df1b9750e",
    "index": 1,
    "friends": [
      {
        "id": 0,
        "name": "Sanders Wilcox"
      },
      {
        "id": 1,
        "name": "Orr White"
      }
    ]
  }
]

We will create one program to read the contents of this JSON file using GSON.

Convert the JSON file to POJO :

At first, we need to convert the JSON file to simple Java object files and use them with GSON.
It has created two files: User.java and Friend.java
User.java :

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Friend {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("name")
    @Expose
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Friend.java :

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Friend {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("name")
    @Expose
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Building the full Application :

If you see the JSON object, it contains an array of User objects and each User object holds one array Friend.

The main class will look like below :

import com.google.gson.Gson;

import java.io.*;

public class ExampleJSON {
    public static void main(String[] args) {
        Gson gson = new Gson();
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new FileReader("C://example.json"));
            User[] finalData = gson.fromJson(bufferedReader, User[].class);

            for (int i = 0; i < finalData.length; i++) {
                System.out.println(finalData[i].getId());
                for (int j = 0; j < finalData[i].getFriends().size(); j++) {
                    System.out.println("id : " + finalData[i].getFriends().get(j).getId() + " name : " + finalData[i].getFriends().get(j).getName());
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Remember to replace the location of the .json file in the FileReader constructor.

If you run the above program, it will print the below output :

5c076be16f76894c3ffc838b
id : 0 name : Clayton Perry
id : 1 name : Willa Moore
5c076be1a83a0d7df1b9750e
id : 0 name : Sanders Wilcox
id : 1 name : Orr White

It printed out the contents of the example.json file.

Conclusion :

As we have seen that we can easily read the information of a JSON file and store it in simple POJO objects.
Try to create different JSON objects and read them using GSON. If you have any queries, drop one comment below.

 

You might also like :

Categories: java

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *