Detail the use of XML Object Json conversion and Xstream

  • 2020-06-03 06:37:29
  • OfStack

Detail the use of XML,Object,Json conversion and Xstream

1. Features of Xstream:

Here is a direct quote from the official account of Xstream:

Flexible and easy to use: Provides a simple, flexible and easy to use unified 1 interface at a higher level, without requiring users to know the low-level details of the project No mapping: Most objects can be serialized and deserialized without mapping High speed and stability: The most important design goals are fast parsing and low memory footprint to make it suitable for large object processing or information throughput demanding systems Clear and understandable: The reflection mechanism is adopted to obtain XML files without redundant information. The generated XML file is more concise than the local Java serialization product, and the format is clearer and easier for users to read No modification: Fully serializes all internal fields, including private and final types. Support non-public and inner classes, which can have no default constructor Easy integration: By implementing a specific interface, XStream can be serialized and de-sequenced directly with any other tree structure (not just XML format) Flexible transformation: The transformation strategy is customizable, allowing users to customize how special types of objects are stored in XML format. Error handling: When an exception is caused because the XML data is not valid, detailed diagnostic information is provided to help resolve the problem.

2. Initialize the XStream class

Xstream is simple because it provides entry to Series 1 and the main class XStream serves as the entry point for all projects. It integrates key components in one, providing a simpler and easier to use API operation.

We can initialize the operation with the following statement:

XStreamxstream = new XStream();

By default, XStream USES the Xpp3 library, which is a very efficient XML full parsing implementation. If you do not want to rely on the Xpp3 library, you can also use a standard JAXP DOM parser, which can be initialized with the following statement:

// The XPP3 library is not used
XStreamxstream = new XStream(new DomDriver());

This instance of xstream is thread-safe and can be invoked by multiple threads for Shared use. Reference com. thoughtworks. xstream. io. xml package, will find the system to provide a variety of identity parser for us to choose, including, DomDriver, JDomDriver, StaxDriver and so on.

As mentioned earlier, Xstream provides support for Json because Xstream has two Driver built in:

1.JsonHierarchicalStreamDriver: Does not rely on other class libraries, only implement obj- > JSON
2.JettisonMappedXmlDriver: Relies on the jettison library to implement JSON- > obj or obj- > JSON

When dealing with Object with the same setting, the two KINDS of Driver will get different JSON strings. The string of JsonHierarchicalStreamDriver is more concise, just as the official website says.

JsonHierarchicalStreamDriver has a small problem -- the default output is formatted JSON strings, which are structured with Spaces, line breaks, and no decorations are provided.

3. Common methods:


xStream.toXML(object) : Converts an object to XML , Json . 
xStream.toXML(obj, outputStream): Transform objects XML , Json And encapsulates the output stream. 
xStream.toXML(object, writer):  Transform objects XML , Json And sealed into the stream. 
xStream.fromXML() Will: XML , Json Converted into an object, which this method accepts File , InputStream , Reader , String , URL Parameter of type. 
xStream.alias("news", News.class) : Creates an alias for the specified class name. 
xStream.useAttributeFor(News.class, "id") Will: id Set to  News Attribute of the element. 
xStream.aliasField("other", BookShelf.class,"remark"): Modify node name , will BookShelf In the class remark The node name is changed to other . 
xStream.addImplicitCollection(BookShelf.class, "books") : Removes the parent of a collective node. 
xStream.aliasAttribute(" The name ", "name") : to modify an attribute name , for name. 

4. Example 1: Convert the object to XML


/** 
  *  Convert the object to Xml Formatted string  
  * @param object  To convert Xml The object of  
  * @return String:Xml Formatted string  
  */ 
  public static String convertObject2Xml(Object object) { 
   xStream=new XStream(); 
   xStream.alias("news", News.class);// Modify the element name  
   xStream.useAttributeFor(News.class, "id");// will id Set to News Attributes of the element  
   return xStream.toXML(object);    
  } 

5. Example 2: Converts the XML image to an object


/** 
   *  Will become Xml Convert the formatted string to Java object  
   * @param inputStream  To convert Java The object's inputStream 
   * @return String:Xml Formatted string  
   */ 
  public static Object convertXml2Object(InputStream inputStream) { 
    xStream=new XStream(); 
    xStream.alias("news", News.class);// Modify the element name  
    xStream.useAttributeFor(News.class, "id");// will id Set to News Attributes of the element  
    return xStream.fromXML(inputStream);// This method can also be used to xml Converted to map 
  } 

6. Example 3: Convert the object to Json


/** 
   *  Convert the object to Json Formatted string  
   * @param object  To convert Json The object of  
   * @return String:Json Formatted string  
   */ 
  public static String convertObject2Json(Object object) {    
      xStream = new XStream(newJsonHierarchicalStreamDriver() { 
      publicHierarchicalStreamWriter createWriter(Writer out) { 
        // Delete the root node  
        return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE); 
      } 
    });   
    return xStream.toXML(object);    
  } 

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: