Archive

Posts Tagged ‘XML’

Serializing Java-Objects to XML and JSON using XStream

June 6th, 2009
One of the great benefits when working with Java is the fact that there exists a library for almost everything. Today I’d like to present one of those libraries: XStream!

XStream is a simple but very useful library when you want to serialize Java-Objects to XML (or JSON) and read them back again. Of course it would not be much effort to do that on your own when knowing about the concepts of Reflection and Recursion, but why reinventing the wheel when thoroughly tested and widely used code is already available?

The ease of use of the XStream-library can be described best by providing an example.

Let’s suppose we have the following class:

 Java |  copy code |? 
01
package com.java_blog.xStreamTest;
02
 
03
public class Person {
04
 
05
	private String firstName;
06
	private String lastName;
07
 
08
	public Person(String firstName, String lastName) {
09
		super();
10
		this.firstName = firstName;
11
		this.lastName = lastName;
12
	}	
13
}


and this TestCode:

 Java |  copy code |? 
01
package com.java_blog.xStreamTest;
02
 
03
import com.thoughtworks.xstream.XStream;
04
 
05
public class Test {
06
	public static void main(String[] args) {
07
 
08
		Person germanChancellor = new Person("Angela", "Merkel");
09
		Person usPresident = new Person("Barack", "Obama");
10
 
11
		XStream xStream = new XStream();
12
		xStream.alias("Person", Person.class);
13
 
14
		StringBuilder sb = new StringBuilder();		
15
		sb.append(xStream.toXML(germanChancellor));
16
		sb.append("\n");
17
		sb.append(xStream.toXML(usPresident));		
18
		System.out.println(sb);		
19
	}
20
}

output:
<Person>
  <firstName>Angela</firstName>
  <lastName>Merkel</lastName>
</Person>
<Person>
  <firstName>Barack</firstName>
  <lastName>Obama</lastName>
</Person>


Without using the alias in line 12, the <Person>-tag would look quite ugly: <com.java__blog.xStreamTest.Person>

If you prefer JSON over XML, simply invoke another XStream-constructor:

 Java |  copy code |? 
1
XStream xStream = new XStream(new JsonHierarchicalStreamDriver());

output:
{"Person": {
  "firstName": "Angela",
  "lastName": "Merkel"
}}
{"Person": {
  "firstName": "Barack",
  "lastName": "Obama"
}}


Further examples and features as well as limitations can be found on the XStream-project-page.

Happy Coding,

Tino.


Share/Save/Bookmark

tino Java, Libraries , , , ,