Usage of GSon in Java to Read/Write JSON

Rajnilari2015
Posted by in Others category on for Beginner level | Points: 250 | Views : 7019 red flag
Rating: 4.67 out of 5  
 3 vote(s)

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.


 Download source code for Usage of GSon in Java to Read/Write JSON

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

D:\Java\jdk1.8.0_45\bin>echo %CLASSPATH%
D:\Java\jdk1.8.0_45\jre\lib\*.jar;D:\Java\jdk1.8.0_45\jre\lib\gson-2.3.jar;

If you are new to JAVA and want to know about how to setup the CLASSPATH or what it is , here is a nice article about the same

Using the code

First of all let us create a Candidate Entity as under

//Candidate.java
public class Candidate {

	private String candidateName = "";
	private String candidateRollNumber = "";
	private String password = "";
	private String examType = "";

	public Candidate(String candidateName, String candidateRollNumber, String password,String examType){

           this.candidateName = candidateName;
           this.candidateRollNumber = candidateRollNumber;
           this.password = password;
           this.examType = examType;
        }
	
	@Override
	public String toString() {
	return "CandidateInformation [CandidateName=" + candidateName + ", RollNumber=" + candidateRollNumber + ", Password=" + password + ", ExamType=" + examType + "]";
	}
}

It's a simple Java Bean Class that exposes four properties about which we will generate the information.

WRITE OPERATION

Now let use write the below (WRITE OPERATION)

//GSonExperiment.java

import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import com.google.gson.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GSonExperiment {
	final String FILEPATH =  "D:\\candidate.json";		
	//Method: insertCandidate ->Write operation
        //Purpose: Inserts a candidate
	public void insertCandidate(Candidate candidate){
		Gson gson = new Gson();
		
		// convert candidate object to JSON format
		String candidateJSON = gson.toJson(candidate);
		try {
		      //write converted json data to a file named "candidate.json"
		      FileWriter writer = new FileWriter(FILEPATH,true);
		      writer.append(System.getProperty("line.separator") + candidateJSON);	
		      writer.close();
		     } catch (IOException e) {e.printStackTrace();}
	} //end insertCandidate	
}

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.

Output

//candidate.json

{"CandidateName":"Niladri","CandidateRollNumber":"1","Password":"abcd","ExamType":"Java"}
{"CandidateName":"Neo","CandidateRollNumber":"2","Password":"123","ExamType":"Java"}
{"CandidateName":"Angenia","CandidateRollNumber":"3","Password":"mnop","ExamType":"Computer Architecture"}

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"

	//Method: getAllCandidateInfo
     //Purpose: Get all candidates information
	public List<Candidate> getAllCandidateInfo(){
	Gson gson = new Gson();
	String  thisLine = null;
	List<Candidate> lstCandidates = new ArrayList<Candidate>();
	String candidateName = "";
	String candidateRollNumber = "";
	String password = "";
	String examType = "";			
			
	try{
	      BufferedReader br = new BufferedReader(new FileReader(FILEPATH));
				
		//reading one by one line from the file
		while ((thisLine = br.readLine()) != null) {

		if(thisLine != null && !thisLine.isEmpty())
		{

		JsonParser jParser = new JsonParser();
    		JsonObject jObject = (JsonObject) jParser.parse(thisLine); 

		// add elements in the Candidates Collection
	candidateName =  jObject.get("CandidateName").toString().replace("\"","");
	candidateRollNumber =  jObject.get("CandidateRollNumber").toString().replace("\"","");
	password =  jObject.get("Password").toString().replace("\"","");
	examType =  jObject.get("ExamType").toString().replace("\"","");
	lstCandidates.add(new Data(candidateName,candidateRollNumber,password,examType)); 
		}									
	}//end while
       }catch (IOException e) {e.printStackTrace();}
      return lstCandidates;
}

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

//Method: getFilterCandidateInfo
//Purpose: Get candidates filtered by RollNumber
public List<Candidate> getFilterCandidateInfo(String rollNumber){

	return getAllCandidateInfo()
	.stream() //converts the List to Stream
	.filter(rn -> rn.equals(rollNumber)) //Performs the Filter Operation
	.collect(Collectors.toList());//converts stream to List	

}

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())

References

a)Java Script Object Notation(JSON)

b)Google Gson(Gson)

Conclusion

Hope this will be helpful.You can find the zipped files attached herewith.Thanks for reading the article.

Page copy protected against web site content infringement by Copyscape

About the Author

Rajnilari2015
Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team


Login to vote for this post.

Comments or Responses

Posted by: Crniranjanraj on: 9/30/2015 | Points: 25
helped me in my current project.thanks

Login to post response

Comment using Facebook(Author doesn't get notification)