Month: July 2013

JSON Jackson Example


JSON has been a popular data exchange format for some time now. What impresses me the most is it’s light weightedness and simplicity.Java has it’s fair share of JSON libraries which can be used for processing and creating JSON. Amongst all, Jackson beats the competion in popularity in the developer community.

Jackson is a multi-purpose Java library for processing JSON data format. Jackson aims to be the best possible combination of fast, correct, lightweight, and ergonomic for developers – From the Jackson Wiki

Here, i will demonstrate how to create JSON string from Java Object and vice versa. Without any further nonsense, lets get started with the example.

First let’s create the custom Employee object which we will use to generate the JSON Output. The Employee object comprises of an id(integer), name(String), department – represented by another custom class ‘Department’ and list of teammates(arraylist of Strings).

Department department = new Department(1, "IT");
List teamMates = new ArrayList() {
private static final long serialVersionUID = 1L;
{
add("karian");
add("jmm");
add("cp");
}
};
Employee employee = new Employee(101, "TJ", department, teamMates);

Now we will use the Jackson Library class ‘ObjectMapper’ to generate the JSON equivalent for the Employee Object constructed above.

ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(employee);

That’s it and this returns the following JSON output.

{"employeeId":101,"teamMates":["karian","jmm","cp"],"employeeName":"TJ","department":{"departmentId":1,"departmentName":"IT"}}

Let’s use the same generated JSON output to create the Employee object

String json = "";// Assign the above string here
ObjectMapper mapper = new ObjectMapper();
Employee employee = mapper.readValue(json, Employee.class);


The readValue() method accepts two parameters, the json input as String and the Class whose instance it should generate from the json input.

Wasn’t that easier than you thought ?

You can download the full code from this git repo : https://github.com/jollyarun/jackson-demo.git

Cheers !!
The Nonsense Blogger !!

Advertisements