Thursday, February 14, 2013

Json to Object by Jackson

To binding a JSON string to an object and vice versa we can use the library Jackson. Do not like the Marshaller and Unmarshaller in binding a XML to Object, we do not need any annotations in bean.
The User.java likes this:
public class User {

 private String userName;
 
 private String password;

 public User() {}
 
 public User(String userName, String password) {
  super();
  this.userName = userName;
  this.password = password;
 }

And the Group.java likes this:
public class Group {

 private String groupName;
 
 private List<User> lstUser;

 public Group() {}
 
 public Group(String groupName, List<User> lstUser) {
  super();
  this.groupName = groupName;
  this.lstUser = lstUser;
 }

Note: in these classes, we overload the default constructor, so we need to define the default constructor for Jackson Without this default constructor, we will receive an error message:
Exception in thread "main" org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class com.lapth82.jackson.example.bean.Group]: can not instantiate from JSON object (need to add/enable type information?)

To work with Jackson, just follow these steps:
Initializing Jackson:
ObjectMapper mapper = new ObjectMapper();

Writing an object to JSON:
String json = mapper.writeValueAsString(lstGroup);

Binding a JSON to Object:
List lstGroup = 
 mapper.readValue(
  json, 
  new TypeReference<List<Group>>(){}
);
at line 4: to bind a JSON to a list we must use TypeReference

See also: working with XML by using Marshaller and Unmarshaller

For the demonstration, please download Source code from my repository on Github

No comments:

Post a Comment