Reading JSON Files with Gson

Seyed Sahil
2 min readDec 4, 2020

Hello there and welcome to my new article on Java Programming. Today I will show you how to read data from a JSON file by using Gson library. Don’t think too much, it is very simple.

Going forward I will be using a Maven project and I would recommend you to download demo project source code from my GitHub.

About Gson…

Gson is a Java serialization/deserialization library which is used to covert Java objects to JSON representation or JSON representation to Java objects.

Adding the Dependency…

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>

Create the Resource File…

Say, I have a small shop and I am selling fruits. I would like to store information like name, count, etc. for each kind of fruits and maintain a list. I am going to name the file as fruits with extension .json and store it in my resources folder.

Loading the Data to Java Application…

Here we have to use the path of the JSON file we created earlier and using Gson we can load the data into a list of maps. Where each map will hold the stock information the list will have all the stock information.

Traversing the List…

If we take a closer look at the above lines of code, I have used generics and didn’t mentioned what should be the data type on RHS of the map containing stock information. Lets see what is the type of values in RHS of map containing stock information. In the JSON file, we can see that the RHS have three data types — String, Boolean and Real number.

So lets take a look if those data types can be identified from our Java application.

And take a look at the output generated.

{name=Ford, available=true, count=2.0}
java.lang.String - java.lang.String
java.lang.String - java.lang.Boolean
java.lang.String - java.lang.Double
{name=Ferrari, available=false, count=0.0}
java.lang.String - java.lang.String
java.lang.String - java.lang.Boolean
java.lang.String - java.lang.Double
Process finished with exit code 0

As we can see from the generated output, the types of RHS value of each items in the list has been identified which is respectively String, Boolean and Double 🙂

Now we have loaded the data we can process it as we need.

Looking for the Source Code ?

/seyedsahil/gson-file-demo/

Thank you for reading

Seyed Sahil

Originally published at http://sydlabz.wordpress.com on December 4, 2020.

--

--

Seyed Sahil

Coding Since 2011, Software Engineer, Game Developer, Artist, Photographer. Passionate about Security and Web Technologies. Favourites — C, Java, Javascript.