Milan Dinic's blog
This blog is about software development and tech problems and solutions. It is not restricted to any technology, although I guess it will contain more posts related to java and java based technologies, since I'm quite a fan of java.

Friday, November 20, 2009

Jackson - Marshaller for JSON

A while ago I was writing how to handle json in java. It was a low level approach, now I found much more sophisticated way to handle json in Java. Of course, it is a library, it is called jackson, and it is capable of serializing json to java class instance and vice versa. I'll show how easy it is to work with this library by example. Lets assume we have maven 2 project, then all that is it needed to run jackson are two extra dependencies:

<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-lgpl</artifactId>
<version>1.3.0</version>
</dependency>

<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-lgpl</artifactId>
<version>1.3.0</version>
</dependency>


Here is a simple model that will be marshaled and un-marshaled:

public class User {
public enum Gender {
MALE, FEMALE
};
public Name name;
public boolean verified;
public Gender gender;
public byte[] userImage;

//getters and setters
}

public class Name {
private String first;
private String last;

//getters and setters
}

Jackson does not require any XML or any other kind of mappings or annotations to perform serialization. Here is the example how simple it is to work with jackson library:

ObjectMapper mapper = new ObjectMapper();
final User user = new User();
user.setVerified(false);
user.setGender(Gender.MALE);
user.setUserImage(new byte[] {0, 1, 2, 3});
final Name name = new Name();
name.setFirst("John");
name.setLast("Smith");
user.setName(name);

//write to file
mapper.writeValue(new File("/tmp/user.json"), user);

//read form file
final User newUser = mapper.readValue(new File("/tmp/user.json"), User.class);


After executing this code content of the file '/tmp/user.json' will be:

{"verified":false,"gender":"MALE","userImage":"AAECAw==","name":{"first":"John","last":"smith"}}


Find out more about jackson at jackson web site.

0 comments:

Post a Comment