Using XStream is the implementation of XML and Java Object Conversion (1)--Introduction and Getting Started example

Source: Internet
Author: User
Tags stringbuffer

First, Brief introduction

XStream is an open source framework developed by ThoughtWorks for the transformation of XML data into Java objects and JSON data. It does not require schema or other mapping files to be able to convert between Java objects and XML files, API calls are very convenient, and the extension is powerful.

1 , XStream the characteristics

A) flexible and easy-to-use: Provides a simple, flexible, easy-to-use unified interface at a higher level without the user needing to know the underlying details of the project

b) No mapping required: Most objects can be serialized and deserialized without mapping

c) High-speed stability: The most important indicator to achieve in the design is the resolution speed, occupies less memory, so that it can be used for large object processing or high information throughput requirements of the system

D) Clear and understandable: the project uses the reflection mechanism to obtain XML files without redundant information. The resulting XML file is more concise, more legible, and easier for users to read than the native Java serialization product

e) No modification required: full serialization of all internal fields including private and final types. Non-public classes and inner classes are supported, and classes can have no default constructors.

f) Ease of integration: By implementing a specific interface, XStream can be serialized and deserialized directly with any other tree structure (not just in XML format)

g) Flexible Conversions: Conversion strategies can be customized, allowing users to customize how special types of objects are stored in XML format.

h) Error handling: When an exception is caused by an illegal XML literal, detailed diagnostic information is provided to help with the problem.

2 , application situations

A) persistence of data Objects

b) Data exchange

c) configuration file

3 , architecture Analysis

A) converters (converter)

When XStream encounters an object that needs to be converted, it delegates to the appropriate converter implementation, XStream provides a variety of converter implementations for common types, including basic data types, String, collections, Arrays, NULL, Date, and so on.

The XStream provides the default converter, which is used when the data object that needs to be converted does not have a matching converter. is to automatically map all fields within an object through a reflection mechanism.

b) IO (input/output)

XStream is abstracted from the underlying XML data through interfaces Hierarchicalstramwriter and Hierarchialstreamreader, which are used for serialization and deserialization operations, respectively.

This feature allows XStream to read data directly from the data stream using an XML parsing class, or to extract data directly from an existing structure (such as the DOM). If the XML data manipulated by XStream has been partially processed by other XML parsing classes (such as instances of the SOAP Class), this avoids the re-parsing operations at our level.

c) Context (context Reference)

When XStream serializes or deserializes an object, it creates two classes Marshallingcontext and Unmarshallingcontext, which process the data and delegate the appropriate converters.

XStream provides a three default implementation of the context, with subtle differences between them. The default value can be changed by Method Xstream.setmode (), and one of the following parameters needs to be passed:

i) xstream.xpath_references, (the default) is used by XPATH to identify duplicate references. The resulting XML has minimal clutter.

II) xstream.id_references, using ID citations to identify duplicate references. In some cases, such as using handwritten XML, this will be easier to manipulate

III) Xstream.no_references, this situation will lose support for graphical objects, only the object as a tree structure. Repeated references are considered to be two different objects, and circular references can cause an exception to occur. This mode is faster compared to the above two modes, and memory consumption is more

d) Facade (unified entrance)

The main class XStream is used as an entry point for all projects. It integrates the important components mentioned above to provide more easy-to-use API operations.

II. Resource Web site

Project homepage:

http://xstream.codehaus.org/

Online Help Documentation: http://xstream.codehaus.org/javadoc/index.html

Lib and source code download: http://xstream.codehaus.org/download.html

Three, the attention matters:

1 , XStream the Java object is serialized as XML data, you do not care whether the property field is final , Private type, and do not care if there is a corresponding Get/set method, not to mention whether you have a default parameterless construction method.

2 , the project's Classpath there should be 3. Package : xstream-[version].jar,xpp3-[version].jar,xmlpull-[version].jar.

Iv. examples and introduction of use Getting Started

1 , the sample code

Java code
  1. Import Com.thoughtworks.xstream.XStream;
  2. Import Com.thoughtworks.xstream.io.xml.DomDriver;
  3. Import Com.thoughtworks.xstream.io.xml.StaxDriver;
  4. public class Xstreamtest {
  5. public static void Main (string[] args) {
  6. Person p = new person ();
  7. P.sex = new StringBuffer ("Unknown");
  8. P.set ("Like Flowers");
  9. P.age = 70;
  10. System.out.println ("Person object before conversion p=" +p);
  11. When you create a XStream instance, the above 3 jar packages must all have
  12. XStream XStream = new XStream ();
  13. The XPP3 library is not needed here, but instead uses the standard JAXP DOM to parse the XML
  14. XStream XStream = new XStream (new Domdriver ());
  15. You don't need a XPP3 library here, but you need to use Java 6.
  16. XStream XStream = new XStream (new Staxdriver ());
  17. String xml = Xstream.toxml (p);
  18. System.out.println ("convert generate XML string = =" +xml);
  19. person P2 = (person) xstream.fromxml (XML);
  20. System.out.println ("Person object after conversion p2=" +P2);
  21. }
  22. }
  23. Class person{
  24. private String name;
  25. int age;
  26. public StringBuffer sex;
  27. public void Set (String name) {
  28. THIS.name = name;
  29. }
  30. Public String toString () {
  31. Return "{name=" +name+ "; age=" +age+ "; sex=" +sex+ "}";
  32. }
  33. }

Operation Result:

The person object before conversion p={name= such as Flower; age=70;sex= unknown}

Convert generate XML string ==<?xml version= "1.0"?><cn.tjpu.zhw.xml.person><name> like flowers </name><age>70 </age><sex> Unknown </sex></cn.tjpu.zhw.xml.Person>

The person object after conversion p2={name= such as Flower; age=70;sex= unknown}

2 , create a XStream object

a) Parameterless constructor, default using XPP3 package

Java code
    1. When you create a XStream instance, the above 3 jar packages must all have
    2. XStream XStream = new XStream ();

b) A parameter constructor that uses the standard JAXP DOM

Java code
    1. Instead of XPP3 and xmlpull libraries, the XML is parsed using the standard JAXP dom.
    2. XStream XStream = new XStream (new Domdriver ());

c) A parameter constructor that uses Stax to parse XML

Java code
    1. You don't need a XPP3 library here, but you need to use Java 6.
    2. XStream XStream = new XStream (new Staxdriver ());

3 to convert a Java object to an XML string

String xml = Xstream.toxml (p);

The result is:

XML code
    1. <?xml version= "1.0"?>
    2. <cn.tjpu.zhw.xml.Person>
    3. <name> such as Flowers </name>
    4. <age>70</age>
    5. <sex> Unknown </sex>
    6. </cn.tjpu.zhw.xml.Person>

4 to convert the XML into a Java object

person P2 = (person) xstream.fromxml (XML);

Reference article: http://www.doc88.com/p-091909836812.html

Using XStream is the implementation of XML and Java Object Conversion (1)--Introduction and Getting Started example

Related Article

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.