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 http://json.org/.

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;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;

public class Person {

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

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

public String getName() {
return name;
}

public void setName(String name) {
this.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) {
this.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);
System.out.println(jsonString);

// Read
Person newPerson = (Person)xstream.fromXML(jsonString);
System.out.println(newPerson.getName());
System.out.println(newPerson.getAge());
System.out.println(newPerson.getEmail());
}
}

Sample output:

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

jason
30
[email protected]


Trackback URL


2 Trackback(s)

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

RSS Feed for This PostPost a Comment