Tag Archives: GSON

JSON Parsers


JSON (JavaScript Object Notation) is most popular for NoSQL data storage, data exchange format between browsers and web servers and latest framework also use for communication over networks.

For Example :

  • All latest browsers natively support parse JSON data to java script to display over page.
  • REST Service support one of MediaType is JSON to exchange data between browsers or client application to servers where these REST Services are deploy.
  • Some latest framework like Elasticsearch, Logstash, Kibana, Kafka ,Filebeat etc. are used JSON for internal storage and data exchange over network between servers.

All these above cases, JSON data language independent feature provides communication compatibility between different type frameworks and servers. All these frameworks and servers implemented by one of computer language which provides JSON API’s by internally or consumed third party library for parsing and generation.

Here we will focus mainly on Java based JSON APIs which provide various choices for parsing and JSON generation on different cases from JAVA objects.

The Java Open Source Community developed some JSON APIs which offers more choices and flexibility to work with JSON. Here is list of some well-known JSON APIS:

  • Jackson
  • GSON
  • Boon
  • JSON.org

See also : Serialization and Deserialization of JSON to/from JAVA.

JACKSON

Jackson is most popular Java JSON APIs which provide several choices to work with JSON. It contains two different parsers:

  • JsonParser : This is pull parser, which parse one token at a time. These token generated by JsonGenerator.
  • JsonMapper : This parser is use convert customize JSON to/from JAVA object. It also parse data in tree model.

You can follow this link to more detail about Jackson JSON APIs : https://github.com/FasterXML/jackson

GSON

GSON provides flexible Java JSON API developed by Google. GSON APIs are able to work with arbitrary Java objects including pre-existing objects that you do not have source code. It also supports for handling complex objects with generics and deep inheritance. GSON is having three different parsers for JSON Java APIS:

  • Gson class : It can parse JSON into custom Java objects.
  • JsonReador : It’s pull JSON parser, which parse one token at a time.
  • JsonParser : It’s parser JSON into a tree structure of GSON specific Java Objects.

You can follow this link to more detail about GSON JSON APIs : https://github.com/google/gson

Boon

Boon is a standard JSON API in Groovy . It is similar to JACKSON but not only apecific for Java JSON API. It’s complete tool kit to working with data, file process and REST services etc. Boon contains the following Java JSON parsers:

  • ObjectMapper :This parser is use to parse JSON into custom objects and Java Maps.

You can follow this link to more detail about BOON JSON APIs : https://github.com/boonproject/boon

JSON.org

JSON.org provides the first JSON API developed for Java. It’s easy to use but not flexible and fast as compared to others  Java JSON open source APIs.

As I recommend if your application is too old and using this API then only go with it otherwise you can switch with others above Java JSON APIs.

You can follow this link to more detail about JSON.org JSON APIs : https://github.com/douglascrockford/JSON-java

Here, In my further posts for JSON I will focus on JACKSON and GSON because that are most known JSON APIs used by developers.

You would like to see

Follow below link to see more about JSON Tutorial and JSON issues Solutions:

How to do JSON pretty formatting and Null Serialization (GSON/GsonBuilder)


In previous example use GSON comes with simple JAVA API’s to convert JAVA object to/from JSON and here I will use GsonBuilder to print format JSON and serialize null object values also.

How to convert Java object to / from JSON by (GSON)

Pre-Requisite:

  • JAVA 8
  • Maven 3
  • GSON Jar as below.

GSON Dependency:

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

Convert JAVA object to/from JSON

package gsonexamples;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import model.Employee;

public class GsonConvertJavaToJSON {

	public static void main(String[] args) {
		//Create GSON Object
		//Gson gson = new Gson();
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
		Employee employee=getJavaObject();
		String json=gson.toJson(employee);

        System.out.println("Convert Java Object To JSON");
		System.out.println(json);

		System.out.println("Convert JSON To Java Object");
		employee=gson.fromJson(json,Employee.class);
		System.out.println(employee);

	}
	public static  Employee getJavaObject()
	{
		Employee employee=new Employee("C123","Saurabh" ,"Kumar","Gupta","Tech Lead",50000,"Alpharetta,GA","Dallas, TX","1231231230",null,null);
		return employee;
	}

}

  • GsonBuilder().setPrettyPrinting() :  This api is to generate pretty formatted JSON string.
  • GsonBuilder().searializeNulls() :  This api is to serialize null values in object.
  • GsonBuilder().create(): This api is to create GSON object to Java object to/from JSON.
package model;

import java.util.List;
import java.util.Set;

public class Employee {
private String employeeId;
private String firstName;
private String middleName;
private String lastName;
private String designation;
private int salary;
private String permanentAddress;
private String mailingAddress;
private String mobile;
private Set<Education> educationDetail;
private List<Experience> expericeDetail;

@Override
public String toString() {
	return "Employee [employeeId=" + employeeId + ", firstName=" + firstName + ", middleName=" + middleName
			+ ", lastName=" + lastName + ", designation=" + designation + ", salary=" + salary + ", permanentAddress="
			+ permanentAddress + ", mailingAddress=" + mailingAddress + ", mobile=" + mobile + ", educationDetail="
			+ educationDetail + ", expericeDetail=" + expericeDetail + "]";
}
public Employee(String employeeId, String firstName, String middleName, String lastName, String designation, int salary,
		String permanentAddress, String mailingAddress, String mobile, Set<Education> educationDetail,
		List<Experience> expericeDetail) {
	super();
	this.employeeId = employeeId;
	this.firstName = firstName;
	this.middleName = middleName;
	this.lastName = lastName;
	this.designation = designation;
	this.salary = salary;
	this.permanentAddress = permanentAddress;
	this.mailingAddress = mailingAddress;
	this.mobile = mobile;
	this.educationDetail = educationDetail;
	this.expericeDetail = expericeDetail;
}
//Getter and Setter
}

package model;

public class Education {
private String schoolOrCollegeName;
private String standard;
private String stream;
private double percentage;

@Override
public String toString() {
	return "Education [schoolOrCollegeName=" + schoolOrCollegeName + ", standard=" + standard + ", stream=" + stream
			+ ", percentage=" + percentage + "]";
}
public Education(String schoolOrCollegeName, String standard, String stream, double percentage) {
	super();
	this.schoolOrCollegeName = schoolOrCollegeName;
	this.standard = standard;
	this.stream = stream;
	this.percentage = percentage;
}
//getter and setter
}
package model;

import java.util.Date;

public class Experience {
private String companyName;
private String designation;
private Date startDate;
private Date endDate;
private double salary;
public Experience(String companyName, String designation, Date startDate, Date endDate, double salary) {
	super();
	this.companyName = companyName;
	this.designation = designation;
	this.startDate = startDate;
	this.endDate = endDate;
	this.salary = salary;
}
@Override
public String toString() {
	return "Experience [companyName=" + companyName + ", designation=" + designation + ", startDate=" + startDate
			+ ", endDate=" + endDate + ", salary=" + salary + "]";
}
//getter and setter
}

Output:

Convert Java Object To JSON
{
  "employeeId": "C123",
  "firstName": "Saurabh",
  "middleName": "Kumar",
  "lastName": "Gupta",
  "designation": "Tech Lead",
  "salary": 50000,
  "permanentAddress": "Alpharetta,GA",
  "mailingAddress": "Dallas, TX",
  "mobile": "1231231230",
  "educationDetail": null,
  "expericeDetail": null
}
<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>
Convert JSON To Java Object
Employee [employeeId=C123, firstName=Saurabh, middleName=Kumar, lastName=Gupta, designation=Tech Lead, salary=50000, permanentAddress=Alpharetta,GA, mailingAddress=Dallas, TX, mobile=1231231230, educationDetail=null, expericeDetail=null]

In above JSON output is pretty formatted properly and  serialize null objects for education and experience. In next blog will explain about how to exclude fields while serializing/deserializing to/from JSON by GsonBuilder.

How to exclude fields from JSON while parsing by GSON/GsonBuilder?