Analysis of the Xml,object,json conversion XStream use

Source: Internet
Author: User

Xml,object,json An analysis of transformation Xstream the Use

Please respect other people's labor results, reproduced please specify the source: Analysis of the Xml,object,json conversion XStream use

XStream is a simple library that is used primarily for Java objects, and XML conversion between the. However , XStream also has built-in support for Json .

features of 1.Xstream:

Direct Reference here Xstream The official narrative :

flexible and easy to use: provides a simple, flexible, and easy-to-use unified interface at a higher level without the need to understand the project's Bottom Detail

No mapping Required: Most objects can be serialized and deserialized without the need for mapping

High-speed Stability: The most important indicators to achieve in the design are fast resolution and low memory consumption, so that it can adapt to for large object processing or for systems with high information throughput requirements

clear and understandable: Project Adoption Reflection mechanism to obtain non-redundant information XML file. The resulting XML file is more concise, more legible, and easier for users to read than the native Java Serialization Product

No modification required: full serialization consists of Private and the Final all internal fields, including the type. Supports non-public classes and inner classes, classes can have no default constructors

Easy Integration : by implementing a specific interface,theXStream can be serialized and deserialized directly with any other tree structure (not just XML format)

Flexible Conversions: conversion policies can be customized to allow users to customize how special types of objects are XML format storage.

Error Handling: because XML If the data is not legal and causes an abnormality, detailed diagnostic information will be provided to help with the problem.

2. Initialize the XStream class

say Xstream simply because it provides a unified portal, the main class XStream serves as an entry point for all projects. It integrates important components to provide easier-to-use API operations.

We can use the following statement to initialize the operation:

Xstreamxstream = new XStream ();

by default, XStream will be Adopt XPP3 Library, XPP3 is a very high- performance XML full-resolution implementation. If you don't want to rely on the Xpp3 Library, you can also use a standard JAXP DOM parser that can be initialized with the following statement:

// Do not use XPP3 Library

Xstreamxstream = new XStream (new Domdriver ());

this XStream The instance, which is thread-safe, can be used by multiple threads for invocation and sharing. Referring to the com.thoughtworks.xstream.io.xml Package, the system provides a variety of identity parsers for our selection, including,domdriver, jdomdriver,staxdriver and so on.


mentioned earlier. Xstream provides a Json the support, is because Xstream built-in two + Driver :

1. Jsonhierarchicalstreamdriver: Do not rely on other class libraries, only implement Obj->json

2.jettisonmappedxmldriver : Dependent Jettison class Library to implement Json->obj or Obj->json

Two kinds of Driver get different JSON when dealing with objects of the same setting String, Jsonhierarchicalstreamdriver the string obtained is more concise, as the official website says.

Jsonhierarchicalstreamdriver There is a small problem--The default output formatted JSON string, with spaces in the structure, line wrapping, and no adornment.

3. Common methods:

xStr EAM .toxml (object) : convert object to xml , json

xStr EAM .toxml (obj, outputstream): Span style= "font-family: Song body; Color: #3F7F5F "> convert object xml json and encapsulate it as an output stream.

XStream . ToXML (object, writer): convert an Object XML , Json and is sealed into a write stream.

XStream. FromXml ():will beXML,Jsonconverted to an object, this method acceptsFile,InputStream,Reader,String,URLthe parameters of the type.

XStream . Alias ("News", News. ) class ): creates an alias for the specified class name.

xStr EAM .useattributefor (News. class "id" " id set as news The attributes of the element.

XStream. Aliasfield ("Other", Bookshelf.class,"Remark"):Modify node name,will beBookshelfin the classRemarkthe node name is modified to Other.

Span lang= "en-US" style= "font-family:consolas; Color: #0000C0 ">xstream class "books" " : Remove the parent node of the collective node.

Span lang= "en-US" style= "font-family:consolas; Color: #0000C0 ">xstream .aliasattribute ( " name " "name" " : Modify the properties of the name is the name.

4. Example 1: Converting an object to XML    

/**     * Convert an object into an XML-formatted string     * @param object to be converted to XML     * @return String:xml-formatted string     */public    static String Convertobject2xml (Object object) {       xstream=new xStream ();       Xstream.alias ("News", news.class);//Modify element name       xstream.useattributefor (news.class, "id");//attribute of the element that sets the ID to news       return Xstream.toxml (object);         }

5. Example 2: converting an XML image to an object

/**     * Converts an XML-formatted string into a Java object     * @param inputstream to convert to a Java object inputstream     * @return string:xml-formatted string     * /public    static Object Convertxml2object (InputStream inputstream) {       xstream=new xStream ();       Xstream.alias ("News", news.class);//Modify element name       xstream.useattributefor (news.class, "id");//attribute of the element that sets the ID to news       return  xstream.fromxml (inputstream);//This method can also convert XML to map    }


6. Example 3: Convert an object to Json

/**     * Convert an object to a JSON-formatted string     * @param object to be converted to JSON     * @return String:json-formatted string     */public    static String Convertobject2json (Object object) {                 XStream = new XStream (Newjsonhierarchicalstreamdriver () {            Publichierarchicalstreamwriter Createwriter (Writer out) {                //delete root node               return new Jsonwriter (out, Jsonwriter.drop_root_mode);            }       );          return Xstream.toxml (object);         }


Xml,object,json conversion XStream use

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.