About Siva Reddy

Katamreddy Siva Prasad is a Senior Software Engineer working in E-Commerce domain. His areas of interest include Object Oriented Design, SOLID Design principles, RESTful WebServices and OpenSource softwares including Spring, MyBatis and Jenkins.

Java JSON processing with Jackson

JSON (Javascript Object Notation) is becoming a very popular data exchange format. While developing Web applications using Javascript frameworks like YUI, ExtJS, DOJO etc., we can use either XML or JSON to exchange the data between the client and server. Normally we get the response from the server in terms of java objects. Then in Servlets or Action classes we need to build the JSON from objects and send back to client. To build the JSON response from a Java object we can use Jackson Java JSON Processor which is very easy to use.

Let us see how we can use Jackson Java JSON Processor to convert a java object into JSON and vice versa. We can download the jackson-all-1.6.4.jar from Jackson download page.

The key class which does the marshalling and unmarshalling is org.codehaus.jackson.map.ObjectMapper.

Let us create a User java bean as follows:

package com.sivalabs.json;
import java.util.Date;
 
public class User {
 private String userId;
 private UserName userName;
 private Date dob;
  
 @Override
 public String toString(){
  return "User [dob=" + dob + ", userId=" + userId + ", userName="+ userName + "]";
 }
 //setters and getters
  
}
package com.sivalabs.json;
public class UserName {
 private String firstname;
 private String middlename;
 private String lastname;
  
 @Override
 public String toString()
 {
  return "UserName [firstname=" + firstname + 
  ", lastname=" + lastname+ 
  ", middlename=" + middlename + "]";
 }
 //setters and getters
}

Now let us create an instance of User and marshall it into JSON:

ObjectMapper mapper = new ObjectMapper();
 
UserName userName = new UserName();
userName.setFirstname("Katamreddy");
userName.setMiddlename("Siva");
userName.setLastname("PrasadReddy");
 
User user = new User();
user.setUserId("1");
user.setUserName(userName);
user.setDob(new Date());
 
Writer strWriter = new StringWriter();
mapper.writeValue(strWriter, user);
String userDataJSON = strWriter.toString();
System.out.println(userDataJSON);

This will print the User data in JSON format as :

{
“userId”:”1″,
“userName”:
{
“firstname”:”Katamreddy”,
“middlename”:”Siva”,
“lastname”:”PrasadReddy”
},
“dob”:1300878089906
}

Now let us unmarshall the following user data in json format into User Object:

{
“userId”:”100″,
“userName”:
{
“firstname”:”K”,
“middlename”:”Siva”,
“lastname”:”Prasad”
},
“dob”:1300878089906
}

String userDataJSON = 
"{\"userId\":\"100\",\"userName\":{\"firstname\":\"K\""+
",\"middlename\":\"Siva\",\"lastname\":\"Prasad\"},\"dob\":1300878089906}";
User userFromJSON = mapper.readValue(userDataJSON, User.class);
System.out.println(userFromJSON);

This will print the User object as:

User [dob=Wed Mar 23 16:31:29 IST 2011, userId=100, userName=UserName [firstname=K, lastname=Prasad, middlename=Siva]]

The Date value is marshalled as Timestamp which is the default behaviour. If you want you can change the DateFormat as follows:

DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
SerializationConfig serConfig = mapper.getSerializationConfig();
serConfig.setDateFormat(dateFormat);
DeserializationConfig deserializationConfig = mapper.getDeserializationConfig();
deserializationConfig.setDateFormat(dateFormat);
mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);

Then the User JSON will be:

{
“userId”:”1″,”userName”:
{
“firstname”:”Katamreddy”,
“middlename”:”Siva”,
“lastname”:”PrasadReddy”
},
“dob”:”03-23-2011″
}

We can also marshall a Java Object as json into a file as:

mapper.writeValue(new File("user.json"), user);

This will create a file user.json as:

{
“userId”:”100″,
“userName”:
{
“firstname”:”K”,
“middlename”:”Siva”,
“lastname”:”Prasad”
},
“dob”:1300878089906
}

We can build the User object from user,json as:

User user = mapper.readValue(new File("user.json"), User.class);

Reference: JSON processing using Jackson Java JSON Processor from our JCG partner Siva Prasad Reddy.

Related Articles:

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


two + 9 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books