XStream官方Demo(xml,json,javabean互转)

前端之家收集整理的这篇文章主要介绍了XStream官方Demo(xml,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:

@H_502_13@
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:

@H_502_13@
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:

@H_502_13@
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:

@H_502_13@
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:

@H_502_13@
<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:

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

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

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

The result now becomes:

@H_502_13@
<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:

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

The result now becomes:

@H_502_13@
<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:

@H_502_13@
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:

@H_502_13@
<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:

@H_502_13@
                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:

@H_502_13@
class AuthorConverter implements SingleValueConverter {
}

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

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

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

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

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

@H_502_13@
        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:

@H_502_13@
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:

@H_502_13@
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?

@H_502_13@
<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:

@H_502_13@
 
 

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

@H_502_13@
<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>
原文链接:https://www.f2er.com/xml/297962.html

猜你在找的XML相关文章