Thursday, February 23, 2012

Using Jackson to Serialize JSON

I had developed a library which serialized/de-serialized objects to/from XML. Now I want to port this library to Android and the XML library I used doesn't seem to play nice with Android. I thought of trying out using JSON instead, and I came across Jackson.

Here's an example:

import java.util.LinkedHashMap;


public class JSONTest {

private static class Account {
private String id;
private String name;

public String getId() {
return id;

public void setId(String id) { = id;

public String getName() {
return name;

public void setName(String name) { = name;


public static void main(String[] args) throws Exception {
LinkedHashMap<String, Account> obj = new LinkedHashMap<String, Account>();
Account acc = new Account();

obj.put("account1", acc);

acc.setName("Bank of America");
obj.put("account2", acc);

ObjectMapper mapper = new ObjectMapper();

This generates the following output :

{"account1":{"id":"2","name":"Bank of America"},"account2":{"id":"2","name":"Bank of America"}}

1 comment:

IT said...

I have read your blog its very attractive and impressive. I like it your blog.

JavaEE Training in Chennai JavaEE Training in Chennai

Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

Java Online Training Java Online Training Core Java 8 Training in Chennai Java 8 Training in Chennai