XStream Usage Summary

Source: Internet
Author: User

Recently made WebService message conversion of the public interface to use the Xsream tool Library, write a small summary memo ...

XStream is a Java class library that can convert JavaBean and XML bidirectional, based on the xstream-1.4.4 version of this article. The required maven dependencies are as follows:

<dependency>     <groupId>com.thoughtworks.xstream</groupId>     <artifactid>xstream </artifactId>     <version>1.4.4</version></dependency>

1. Basic Use Method

New Xstream (). ToXML (Bean);

The XML format that is converted using this method is as follows:

<org.xstream.test.People>    <age>10</age>    <name>sedric</name> </ Org.xstream.test.people>

The format consists of the full class name as the root node, the class member variable names, and the variable values that make up the XML element content.

2. Define XML element name, attribute name alias

Normal way:

Xstream.useattributefor (People.class, "age"); Xstream.useattributefor (People.class, "name");// Define class alias Xstream.alias ("People", people.class);//define Field alias Xstream.aliasfield ("Age_alias", People.class, "age");

The XML format that is converted using this method is as follows:

<people age__alias= "Ten" name= "Sedric"/>

Annotation method:

@XStreamAlias ("People") public class people {@XStreamAlias ("Age_alias") @XStreamAsAttributeprivate int age;@ Xstreamasattributeprivate String name;

When using annotations, you must specify XStream parsing annotations as follows:

Specifies that all classes are resolved annotationsxstream.autodetectannotations (true);// Specifies the specified class parsing annotationsxstream.processannotations (People.class);

3.xstream Definition List Underline (_) Double underline (__)

XStream the conversion of special characters is defined in the default conversion mode, the code is as follows:

Xmlfriendlynamecoder.encodename (String name) for (; i < length; i++) {            char c = name.charat (i);            if (c = = ' $ ' | | c = = ' _ ' | | c <= | | C >= 127) {break                ;            }}

XStream Special character conversions for the above range characters, resulting in a single underline becoming double-underlined. How to resolve:

Method 1:str.replaceall ("__", "_");

Method 2:

Construct XStream with XStream's own nonamecoder, which will cause all special characters to be escaped xstream XStream = new XStream (new Xppdriver (New Nonamecoder ())); /using Domdriver and Nonamecoder to construct XStream, this way you can specify the XML encoding XStream XStream = new XStream (New Domdriver ("UTF-8", New Nonamecoder ( )));

Method 3: Customize the Namecoder to convert the specified special characters.

4.XStreamImplicit Annotation Usage

When you need to convert data from a member variable of the collection or map type to an element of the same level of XML, you can use that annotation in that member variable.

@XStreamImplicit (itemfieldname = "list_element") private list<jp> JPS;

The converted XML is as follows:

<people age_alias= "name=" Sedric "><List_Element><gender>man</gender><reason> People silly money more </reason></List_Element><List_Element><gender>woman</gender><reason> Rhetoric </reason></List_Element></People>

Xstreamimplicit annotations have two properties: Itemfieldname refers to the elementname;keyfieldname when the current collection data is converted to an XML element when the collection element is a complex object. The member variable name of the collection element is used as the elementname of the element, and when the collection element is the base data type and the string type, the value specified by Keyfieldname is used as the elementname of the element.

@XStreamImplicit (itemfieldname = "String_element", Keyfieldname = "String_field") Private list<string> stringlist; @XStreamImplicit (itemfieldname = "List_element", Keyfieldname = "List_field") Private list<jp> jps;@ Xstreamimplicit (itemfieldname = "Map_element", Keyfieldname = "Map_field") private map<string, string> Map;

The converted XML is as follows:

<people age_alias= "Ten" name= "Sedric" ><string_element>str1</string_element><string_element >str2</String_Element><List_Element><gender>man</gender><reason> people silly money more </ Reason></list_element><list_element><gender>woman</gender><reason> rhetoric </ Reason></list_element><map_element>value2</map_element><map_element>value1</map_ Element></people>

5.XStreamConverter Annotation Usage

The Xstreamconvert is used to specify the converter (conversion mode) of class and field.

When Xstreamconvert is defined in class, the class and all its member variables (recursive, that is, member variables that conform to the object when the member variable is a composite object) are By default, the converter specified with Xstreamconvert is converted (The specified converter will be used when the Converter.canconvert (Class type) is met).

When Xstreamconvert is defined with field, the field is converted using the Canconvert (Class type) method when it is a base type or string type, or if it is a composite object, The converter is used when all member variables (recursion) of the object satisfy the Canconvert (Class type).

Xstreamconverter Annotation Properties:

Priority Specifies converter precedence, that is, only the priority//maximum converter is used when more than one converter can convert the current object. int priority () default xstream.priority_normal;//The following property, when the value is specified, is passed in as a parameter to the constructor when the converter is constructed. Class<?>[] Types () default {};  String[] Strings () default {};byte[] bytes () default {};char[] chars () default {};short[] shorts () default {};int[] INTs () Default {};long[] longs () default {};float[] floats () default {};d ouble[] Doubles () default {};boolean[] Booleans () Defau lt {};

For converter construction parameters that are more complex, the above properties cannot satisfy the construction parameters, you can use Xstream.registerconverter (parameters: ) or Xstream.registerlocalconverter (parameters: ) to register Converter.

6.xstream support for generics, interfaces, and hyper-classes

For composite type objects, XStream uses Reflectionconverter to convert objects by default. The converter defines a class attribute to be added to the element when the property definition type is inconsistent with the run-time type. The code is as follows:

@XStreamAlias ("Generic") public class Generictypetest {@XStreamAlias ("people") private people people;          generictypetest generic = new Generictypetest ();           SB is a subclass of people, and SB is defined as a member variable SB SB = new SB ("SB"); Generic.setpeople (SB);

The XML to go is as follows:

<generic><people class= "Org.xstream.test.SB" age_alias= "" "Name=" SB "><gender>woman</gender ><reason>resson</reason></People></Generic>

The class attribute can be implemented by a custom converter when the XML is not required for conversion. The implementation method refers to the Abstractreflectionconverter.domarshal method by simply commenting on the following content in the method:

Class DefaultType = mapper.defaultimplementationof (FieldType), if (!actualtype.equals (DefaultType)) {String Serializedclassname = Mapper.serializedclass (Actualtype); F (!serializedclassname.equals (Mapper.serializedClass ( DefaultType)) {//String attributename =//mapper.aliasforsystemattribute ("class");/if (attributename! = null) {//WRI Ter.addattribute (attributename,//serializedclassname),//}}}

Generics, interfaces are not supported for all converter that are default for XML goto Javabean,xstream. If a superclass exists in the XML when there is a subclass attribute, the conversion will occur with an exception, and when the subclass attribute is not included, the conversion succeeds.

Original link

Related: XStream Practical guide

XStream Usage Summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.