For serializing and deserializing Java objects to and from JSON, we are using GSon (also known as Google Gson) which is an open source Java Library
* of Google.In this short article, we will look into as how to perform a simple READ and WRITE operation using GSon.

Introduction

For serializing and deserializing Java objects to and from JSON, we are using GSon (also known as Google Gson) which is an open source Java Library
* of Google.In this short article, we will look into as how to perform a simple READ and WRITE operation using GSon.We are using gson-2.2.3.jar which can be freely downloadable from here.The entire Gson source code is available at https://github.com/google/gson

Environment Setup

First we need to set the CLASSPATH for the gson-2.2.3.jar. As can be figure out, Its done that as reveal as under

At the very begining, we need to import the GSon related packages.Once done, we have to create a new Gson object as under

Gson gson = new Gson();

Next pass the "Candidate" object to the "insertCandidate" function and by using the "toJson" method of Gson class, we convert the candidate object to JSON format.Finally, the FileWriter class writes the JSon object at the specified location.

READ OPERATION

So we are done with our WRITE Operation and are good to go ahead with our READ OPERATION. The below code will demonstrate that (READ OPERATION).We will extend our GSonExperiment.java program by adding the "getAllCandidateInfo"

The Java.io.BufferedReader class is used for reading the text from the file (candidate.json).The JsonParser class of "Gson" parse the JSON object to the JSON elements (in this example a JsonObject).Once done, then we are using the "get" method for fetching the member with the name specified. And finally adding the same to the list

READ OPERATION(FILTER RECORDS)

Last but not the least, we will perform a simple filter operation on "RollNumber" field of the candidate.Let's look at the below code

This is the LAMBDA EXPRESSION of Java 1.8. First we are converting the Collection to Streams , then performing a FILTERING operation (method: Stream.Filter) and finally converting back the stream to the Collection(method: Stream.collect())