XStream官方Demoxml,json,javabean互转

Suppose that our client has defined a base XML file that we should make XStream read/write:

<blog author="Guilherme Silveira">
  <entry>
    <title>first</title>
    <description>My first blog entry.</description>
  </entry>
  <entry>
    <title>tutorial</title>
    <description>
        Today we have developed a nice alias tutorial. Tell your friends! Now!
    </description>
  </entry>
</blog>

Based on the XML file above we shall create some model classes and configure XStream to write/read from this format.

The model

First things first,the classes which shall represent our xml files are shown next,beginning with a simple Blog:

package com.thoughtworks.xstream;

public class Blog {
        private Author writer;
        private List entries = new ArrayList();

        public Blog(Author writer) {
                this.writer = writer;
        }

        public void add(Entry entry) {
                entries.add(entry);
        }

        public List getContent() {
                return entries;
        }
}

A basic author with name:

package com.thoughtworks.xstream;

public class Author {
        private String name;
        public Author(String name) {
                this.name = name;
        }
        public String getName() {
                return name;
        }
}

A blog entry contains a title and description:

package com.thoughtworks.xstream;

public class Entry {
        private String title,description;
        public Entry(String title,String description) {
                this.title = title;
                this.description = description;
        }
}

Although we did not create many getters/setters its up to you to create those you wish or those which make sense.

A simple test

We can easily instantiate a new blog and use it with xstream:

public static void main(String[] args) {

        Blog teamBlog = new Blog(new Author("Guilherme Silveira"));
        teamBlog.add(new Entry("first","My first blog entry."));
        teamBlog.add(new Entry("tutorial","Today we have developed a nice alias tutorial. Tell your friends! Now!"));

        XStream xstream = new XStream();
        System.out.println(xstream.toXML(teamBlog));

}

And the resulting XML is not so nice as we would want it to be:

<com.thoughtworks.xstream.Blog>
  <writer>
    <name>Guilherme Silveira</name>
  </writer>
  <entries>
    <com.thoughtworks.xstream.Entry>
      <title>first</title>
      <description>My first blog entry.</description>
    </com.thoughtworks.xstream.Entry>
    <com.thoughtworks.xstream.Entry>
      <title>tutorial</title>
      <description>
        Today we have developed a nice alias tutorial. Tell your friends! Now!
      </description>
    </com.thoughtworks.xstream.Entry>
  </entries>
</com.thoughtworks.xstream.Blog>

Class aliasing

The first thing we shall change is how XStream refers to thecom.thoughtworks.xstream.Blogclass. We shall name it simplyblog: let's create an alias calledblogto the desired class:

xstream.alias("blog",Blog.class);

Using the same idea,we can alias the 'Entry' class to 'entry':

xstream.alias("entry",Entry.class);

The result Now becomes:

<blog>
  <writer>
    <name>Guilherme Silveira</name>
  </writer>
  <entries>
    <entry>
      <title>first</title>
      <description>My first blog entry.</description>
    </entry>
    <entry>
      <title>tutorial</title>
      <description>
        Today we have developed a nice alias tutorial. Tell your friends! Now!
      </description>
    </entry>
  </entries>
</blog>

Field aliasing

Next we will change the name of the writer tag,but this time we have to use a field alias:

xstream.aliasField("author",Blog.class,"writer");

The result Now becomes:

<blog>
  <author>
    <name>Guilherme Silveira</name>
  </author>
  <entries>
    <entry>
      <title>first</title>
      <description>My first blog entry.</description>
    </entry>
    <entry>
      <title>tutorial</title>
      <description>
        Today we have developed a nice alias tutorial. Tell your friends! Now!
      </description>
    </entry>
  </entries>
</blog>

Implicit Collections

Now let's implement what was called animplicit collection: whenever you have a collection which doesn't need to display it's root tag,you can map it as an implicit collection.

In our example,we do not want to display theentriestag,but simply show theentrytags one after another.

A simple call to theaddImplicitCollectionmethod shall configure XStream and let it kNow that we do not want to write theentriestag as described above:

package com.thoughtworks.xstream;

import java.util.ArrayList;
import java.util.List;

public class Test {

        public static void main(String[] args) {

                Blog teamBlog = new Blog(new Author("Guilherme Silveira"));
                teamBlog.add(new Entry("first","My first blog entry."));
                teamBlog.add(new Entry("tutorial","Today we have developed a nice alias tutorial. Tell your friends! Now!"));

                XStream xstream = new XStream();
                xstream.alias("blog",Blog.class);
                xstream.alias("entry",Entry.class);

                xstream.addImplicitCollection(Blog.class,"entries");

                System.out.println(xstream.toXML(teamBlog));

        }
}

Pay attention to theaddImplicitCollectionmethod call: it describes which class and which member variable shall assume the behavIoUr we described.

The result is almost what we wanted:

<blog>
  <author>
    <name>Guilherme Silveira</name>
  </author>
  <entry>
    <title>first</title>
    <description>My first blog entry.</description>
  </entry>
  <entry>
    <title>tutorial</title>
    <description>
        Today we have developed a nice alias tutorial. Tell your friends! Now!
    </description>
  </entry>
</blog>

Just as a side note: An array or a map can also be declared as implicit.

Attribute aliasing

The next step is to set thewritermember variable as an XML attribute. In order to do this,we shall tell XStream to alias thewriterfield of theBlogclass as an "author" attribute:

                xstream.useAttributeFor(Blog.class,"writer");
                xstream.aliasField("author","writer");

And Now it leaves us with one problem: how does XStream converts an Author in a String so it can be written as a XML tag attribute?

Attributes cannot be written for types that are handled by Converter implementations,we have to use aSingleValueConverterand implement our own converter for the Author:

class AuthorConverter implements SingleValueConverter {
}

The first method to implement tells XStream which types it can deal with:

        public boolean canConvert(Class type) {
                return type.equals(Author.class);
        }

The second one is used to extract a String from an Author:

        public String toString(Object obj) {
                return ((Author) obj).getName();
        }

And the third one does the opposite job: takes a String and returns an Author:

        public Object fromString(String name) {
                return new Author(name);
        }

Finally,the entire single value converter,responsible for converting Strings to Objects (Authors in this case) is:

class AuthorConverter implements SingleValueConverter {

        public String toString(Object obj) {
                return ((Author) obj).getName();
        }

        public Object fromString(String name) {
                return new Author(name);
        }

        public boolean canConvert(Class type) {
                return type.equals(Author.class);
        }

}

And let's register this converter:

public class Test {

        public static void main(String[] args) {

                Blog teamBlog = new Blog(new Author("Guilherme Silveira"));
                teamBlog.add(new Entry("first","entries");

                xstream.useAttributeFor(Blog.class,"author");
                xstream.registerConverter(new AuthorConverter());

                System.out.println(xstream.toXML(teamBlog));

        }
}

The result?

<blog author="Guilherme Silveira">
  <entry>
    <title>first</title>
    <description>My first blog entry.</description>
  </entry>
  <entry>
    <title>tutorial</title>
    <description>
        Today we have developed a nice alias tutorial. Tell your friends! Now!
    </description>
  </entry>
</blog>

You have to be aware,that attribute values normally have to be normalized by the XML parser as required by theW3C spec. Leading and trailing whitespaces are normally removed as well as sequential ones! Therefore a deserialized string might differ from the value visible in the XML representation.

Package aliasing

In the example above we have so far always used class aliases for the Blog and Entry type. Sometimes it is necessary to map existing class types to others simply by changing the package name. Let us go back to the first attempt of our tutorial,but this time we alias the package name instead of the individual classes:

Now!"));

        XStream xstream = new XStream();
        xstream.aliasPackage("my.company","org.thoughtworks");
        System.out.println(xstream.toXML(teamBlog));

}

And the resulting XML contains Now the classes with the aliased package names:

<my.company.xstream.Blog>
  <author>
    <name>Guilherme Silveira</name>
  </author>
  <entries>
    <my.company.xstream.Entry>
      <title>first</title>
      <description>My first blog entry.</description>
    </my.company.xstream.Entry>
    <my.company.xstream.Entry>
      <title>tutorial</title>
      <description>
        Today we have developed a nice alias tutorial. Tell your friends! Now!
      </description>
    </my.company.xstream.Entry>
  </entries>
</my.company.xstream.Blog>

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念