Analysis on the use of Xstream for XML, Object, and Json conversion, jsonxstream
XML, Object, Json conversion analysis of Xstream
Please respect others' labor achievements. for reprinting, please indicate the source: XML, Object, Json conversion analysis of Xstream usage
XStream is a simple library, mainly used for conversion between Java objects and XML. However, XStream also has built-in support for Json.
1. Xstream features:
Here we will directly reference the official Xstream statement:
Flexible and easy to use:A simple, flexible, and easy-to-use unified interface is provided at a higher level. You do not need to understand the underlying details of the project.
No ing required:Most objects can be serialized and deserialized without ing.
High speed and stability:The most important indicator to achieve in design is fast resolution and low memory usage, so that it can be applied to large object processing or systems with high information throughput requirements.
Clear and easy to understand:The project uses the reflection mechanism to obtain XML files without redundant information. Compared with the local Java serialization product, the generated XML file is more concise and the format is clearer, making it easier for users to read.
No need to modify:Fully serialize all internal fields, including private and final fields. Supports non-public and internal classes, and the class can have no default constructor
Easy to integrate: XStream can be serialized and deserialized directly with any other tree structure through specific interfaces (not just XML format)
Flexible conversion:The conversion policy can be customized to allow users to customize how special types of objects are stored in XML format.
Error handling:If an exception is caused by an invalid XML data, detailed information is provided to help you solve the problem.
2. initialize the XStream class
Xstream is simple because it provides a unified entry. The main class XStream is used as the entry point for all projects. It integrates important components and provides easy-to-use API operations.
You can use the following statements to initialize an instance:
XStreamxstream = new XStream ();
By default, XStream uses the Xpp3 library, which is a highly 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. You can use the following statement for initialization:
// Do not use the XPP3 Library
XStreamxstream = new XStream (new DomDriver ());
This xstream instance is thread-safe and can be called and shared by multiple threads. Refer to the com. thoughtworks. xstream. io. xml package and you will find that the system provides a variety of identification Resolvers for us to choose from, including DomDriver, JDomDriver, and StaxDriver.
As mentioned above, Xstream provides support for Json because Xstream has two built-in drivers:
1. JsonHierarchicalStreamDriver: Only obj-> JSON
2. JettisonMappedXmlDriver: relies on the jettison class library to implement JSON-> obj or obj-> JSON
The two drivers get different JSON strings when processing objects with the same settings. The strings obtained by JsonHierarchicalStreamDriver are more concise, as said on the official website.
JsonHierarchicalStreamDriver has a small problem-by default, a JSON string with format is output, with spaces and line breaks in the structure, and no modifier is provided.
3. Common Methods:
XStream. ToXML (object): converts an object to XML or Json.
XStream. ToXML (obj, outputStream): converts objects into XML and Json and encapsulates them into output streams.
XStream. ToXML (object, writer): converts an object into XML, Json, and writes it into a stream.
XStream. FromXML (): converts XML and Json into objects. This method accepts parameters of the File, InputStream, Reader, String, and URL types.
XStream. Alias ("news", News.Class): Creates an alias for a specified class name.
XStream. UseAttributeFor (News.Class, "Id"): sets the id as the attribute of the News element.
XStream. AliasField ("other", BookShelf.Class, "Remark"): Modify the node name and the remark node name in the BookShelf class to other.
XStream. AddImplicitCollection (BookShelf.Class, "Books"): removes the parent node of A group node.
XStream. AliasAttribute ("name", "name"): Modify the name of an attribute as the name.
4. Example 1: convert an object to XML
/*** Convert an object to a String in Xml format * @ param object: the object to be converted to Xml * @ return String: xml format String */public static String convertObject2Xml (Object object) {xStream = new XStream (); xStream. alias ("news", News. class); // modify the element name xStream. useAttributeFor (News. class, "id"); // set the id to the attribute of the element of News return xStream. toXML (object );}
5. Example 2: convert an XML image into an object
/*** Convert a String in Xml format to a Java object * @ param inputStream: xml format string */public static Object convertXml2Object (InputStream inputStream) {xStream = new XStream (); xStream. alias ("news", News. class); // modify the element name xStream. useAttributeFor (News. class, "id"); // set the id to the attribute of the element of 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 String * @ param object: Convert the object to a Json object * @ return String: json format 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 );}
JAVA can convert the following xml into JSON
You can use the XStream class library to implement xml ==> java => json
However, in this case, it is still very difficult to directly convert the class library. You need to set many things and debug them.
We recommend that you write a sax Parser to parse your xml into a java object, use Gson, use JSONObject, or use XStream to convert the object to json.
There is no free lunch in the world, and you can only get it here at. Please adopt it
Answers to xstream's question about converting XML into java objects
XStream xStream = new XStream ();
XStream. aliasType ("LoginRsp", LoginRsp. class );
Object o = xStream. fromXML (ClassLoader. getSystemResourceAsStream ("xxx. xml "));
System. out. println (o );