XStream

XStream is a library to serialize objects to XML and vice versa. It must not be used as a XML processor.

The way that XStream serializes and de-serializes objects is by using Annotations. This post will show you how to annotate a class and how to serialize it.

First of all let’s introduce the class:

public class Book { private String isbn; private List author; private String title; private int pages; //class continues... }

This class models a book. It has the ISBN, a list of authors (it’s only a String per author), the title and the number of pages. The point of XStream is that it uses reflection to serialize and de-serialize the objects.
We want to serialize this book to this XML:

<BOOK> <ISBN>978-0-9815316-0-1</ISBN> <AUTHOR>Martin Odersky</AUTHOR> <AUTHOR>Lex Spoon</AUTHOR> <AUTHOR>Bill Venners</AUTHOR> <TITLE>Programming in Scala</TITLE> <PAGES>736</PAGES> </BOOK>

The next step is to annotate the class:

package com.wordpress.j2eethoughts; import com.thoughtworks.xstream.annotations.XStreamAlias; import java.util.List; @XStreamAlias("BOOK") public class Book { @XStreamAlias("ISBN") private String isbn; //no annotations private List author; @XStreamAlias("TITLE") private String title; @XStreamAlias("PAGES") private int pages; //class continues... }

Note that lists must not be annotated. After this, we need to create the facade of XStream:

package com.wordpress.j2eethoughts; import java.util.ArrayList; import java.util.List; import com.thoughtworks.xstream.XStream; public class Main { public static void main(String[] args) { XStream xs = new XStream(); xs.processAnnotations(Book.class); xs.addImplicitCollection(Book.class, "authors", "AUTHOR", String.class); List authors = new ArrayList(); authors.add("Martin Odersky"); authors.add("Lex Spoon"); authors.add("Bill Venners"); Book book = new Book("978-0-9815316-0-1", authors,"Programming in Scala", 736); System.out.println(xs.toXML(book)); } }

And that’s all, now you can serialize any Book object. For de-serialization you must call the method xs.fromXML passing a String to the method.

Advertisements

2 Responses

  1. I use this library in my project too. It’s very easy. I’m waiting the next chapter about the Marshaller’s.

    Congratulations for your blog.

    JM

  2. It’s on my list! I will explain how to create your custom converter.

    Thanks for visiting my blog!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: