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;

import org.codehaus.jackson.map.ObjectMapper;

public class JSONTest {

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

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

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

acc.setId("1");
acc.setName("Chase");
obj.put("account1", acc);

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


ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(obj));
}
}


This generates the following output :

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

No comments: