RSS Feed for This PostCurrent Article

Serialize Java Object to JSON String

In my previous articles, I talked about storing Java object using XStream and Simple, here I am going to do it again, but this time store the Java object using JSON.

There are many tools that can be used for this purpose, e.g. flexjson, JSON Tools, to name a few. You can find a complete list at

Since I already used XStream, here is the code to write and read Java object to and from JSON string using XStream. You need the Jettision StAX parser and StAX API.

import com.thoughtworks.xstream.XStream;

public class Person {

private String name;
private Integer age;
private String email;

public Person(String name, Integer age, String email) { = name;
this.age = age; = email;

public String getName() {
return name;

public void setName(String name) { = name;

public Integer getAge() {
return age;

public void setAge(Integer age) {
this.age = age;

public String getEmail() {
return email;

public void setEmail(String email) { = email;

public static void main(String[] args) {

// Create the instance
XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.alias(”person”, Person.class);

// Write
Person person = new Person(”jason”, 30, “[email protected]”);
String jsonString = xstream.toXML(person);

// Read
Person newPerson = (Person)xstream.fromXML(jsonString);

Sample output:

{"person":{"name":"jason","age":"30","email":"[email protected]"}}

[email protected]

Trackback URL

2 Trackback(s)

  1. From Serialize .NET Object to JSON String | | Nov 21, 2007
  2. From Java + JSON. Пути к дружбе. « шаманские бредни | Dec 10, 2007

RSS Feed for This PostPost a Comment