XStream object-mapping problem in single-case mode

Source: Internet
Author: User

The source of this article: http://blog.csdn.net/chaijunkun/article/details/30257015, reprint please specify. Because I do not regularly collate the relevant blog posts, the corresponding content will be improved. It is therefore highly recommended to view this article in the original source.

Java as an object-oriented language, the processing of structured data can of course also be object, which is related to the conversion tool. For XML files, you often use JAXB 2.0, which is supported by JDK 1.6, plus a framework called XStream. I have encountered some problems in the use of XStream, here to share.


1. Description of the problemin doing the project, in order to improve performance, reduce the frequency of new objects, I began to write XStream as a singleton mode. Whenever you need to serialize an object into XML, or deserialize the XML into an object, get to the XStream instance, and then call the transform API, but find a bug that throws an exception when deserializing two different XML structures in a row.
2. Base Codefirst I wrote a test case, the following is the XStream Singleton pattern and the serialization object and the code implementation of the deserialized XML:
public class TestCase {private static volatile XStream stream= null;public static XStream GetStream () {synchronized (TESTCA Se.class) {if (stream==null) {stream= new XStream ();} return stream;}} public static <T> void ToXML (Object obj, class<t> clazz, outputstream out) {XStream stream= Testcase.getstream (); stream.processannotations (clazz); Stream.toxml (obj, out); return;} public static <T> T FromXml (InputStream in, class<t> clazz) {XStream stream= testcase.getstream (); Stream.processannotations (clazz); Object obj= stream.fromxml (in); Try{return clazz.cast (obj); catch (ClassCastException e) {return null;}}}

I then built the XML file structure with the same two root nodes but a different child node:
Structure 1:
<root date= "2014-06-12 09:28:34.614 UTC" ><demo><element>test1</element></demo>< Demo><element>test2</element></demo></root>

Structure 2:
<root date= "2014-06-12 09:28:34.745 UTC" ><example><element>test1</element></example ><example><element>test2</element></example></root>


Next, the two structures are mapped separately:
Structure 1:
Package Net.csdn.blog.chaijunkun.xml.case1;import Java.util.date;import Java.util.list;import Com.thoughtworks.xstream.annotations.xstreamalias;import Com.thoughtworks.xstream.annotations.xstreamasattribute;import com.thoughtworks.xstream.annotations.XStreamImplicit; @XStreamAlias ("Root") public class Case1 {@XStreamAlias ("date ") @XStreamAsAttributeprivate date date, @XStreamImplicitprivate list<demo> demos;public date getDate () {return Date;} Some getters and setters ...}

Package Net.csdn.blog.chaijunkun.xml.case1;import com.thoughtworks.xstream.annotations.xstreamalias;@ Xstreamalias ("Demo") public class Demo {@XStreamAlias ("element") private String element;//some getters and setters ...}

Structure 2:
Package Net.csdn.blog.chaijunkun.xml.case2;import Java.util.date;import Java.util.list;import Com.thoughtworks.xstream.annotations.xstreamalias;import Com.thoughtworks.xstream.annotations.xstreamasattribute;import com.thoughtworks.xstream.annotations.XStreamImplicit; @XStreamAlias ("Root") public class Case2 {@XStreamAlias ("date ") @XStreamAsAttributeprivate date date; @XStreamImplicitprivate list<example> examples;//some getters and setters ...}

Package Net.csdn.blog.chaijunkun.xml.case2;import com.thoughtworks.xstream.annotations.xstreamalias;@ Xstreamalias ("Example") public class Example {@XStreamAlias ("element") private String element;//some getters and setters ...}

3. Test CasesFor subsequent deserialization, we first serialize the object into an XML file and then deserialize the file again to see if it succeeds.
serialization of struct 1:
public static void Demo1 () throws Filenotfoundexception{demo d1= new demo ();d 1.setElement ("test1");D Emo d2= New demo ();d 2 . SetElement ("Test2"); list<demo> demos= New linkedlist<demo> ();d emos.add (D1);d Emos.add (D2); Case1 c1= new Case1 (); C1.setdemos (demos); C1.setdate (new Date ()); FileOutputStream out1= New FileOutputStream (New File ("D:\\test1.xml")); Try{testcase.toxml (C1, Case1.class, OUT1);} Finally{try {out1.close ();} catch (IOException e) {e.printstacktrace ();}}}

serialization of struct 2:
public static void Demo2 () throws Filenotfoundexception{example e1= new Example (); E1.setelement ("test1"); Example e2= new Example (); E2.setelement ("test2"); list<example> examples= new linkedlist<example> (); Examples.add (E1); Examples.add (E2); Case2 c2= new Case2 (); C2.setexamples (examples); C2.setdate (new Date ()); FileOutputStream out2= New FileOutputStream (New File ("D:\\test2.xml")); Try{testcase.toxml (C2, Case2.class, out2);} Finally{try {out2.close ();} catch (IOException e) {e.printstacktrace ();}}}

save two results for Test1.xml and test2, respectively. XML, the next attempt is to deserialize them:
public static void Demo3 () throws Filenotfoundexception{file f1= new File ("D:\\test1.xml"); FileInputStream fis1= New FileInputStream (F1); Case1 c11= testcase.fromxml (fis1, Case1.class); File f2= New file ("D:\\test2.xml"); FileInputStream fis2= New FileInputStream (F2); Case2 c22= testcase.fromxml (Fis2, case2.class);}

Next, execute the junit test case:
@Testpublic void Dotest () throws Filenotfoundexception{demo1 ();d Emo2 ();d Emo3 ();

The discovery throws the following exception:
Com.thoughtworks.xstream.converters.ConversionException:Element demo of type Net.csdn.blog.chaijunkun.xml.case1.Demo is no defined as field in type NET.CSDN.BLOG.CHAIJUNKUN.XML.CASE2.CASE2---- Debugging information----Class:net.csdn.blog.chaijunkun.xml.case2.case2required-type:net.csdn.blo G.chaijunkun.xml.case2.case2converter-type: Com.thoughtworks.xstream.converters.reflection.ReflectionConverterpath:/root/demoline number:4v Ersion:null-------------------------------at Com.thoughtworks.xstream.converters.reflection.AbstractReflecti Onconverter.writevaluetoimplicitcollection (abstractreflectionconverter.java:403) at Com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.doUnmarshal ( abstractreflectionconverter.java:334) at Com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.unmarshal ( abstractreflectionconverter.java:234) at Com.thoughtworks.xstream.core.TreeUnmarshaller.convert(treeunmarshaller.java:72) ...... 

in the error message, path indicates that the two-level node to be analyzed is demo, whereas the previously specified structure 2 of the two-level node is example, in fact the Test2.xml two-level node is also example. This indicates that there is no problem with serializing the output. The problem is with deserialization. Based on the error message, the XStream only stores the structure of the first deserialization configuration, and the second call does not update the associated annotation configuration (even if the processannotations annotation is called).
4. Workaroundfor the failure of the singleton mode, the second step is to change it to the Factory mode only:
public static XStream GetStream () {return new XStream ();}

at this point, two deserialization is normal.
due to some extension functions, a special XStream Driver is implemented in its own code, which needs to be injected into the xstream construction process, so the code is written uniformly into the GetStream () method, So that every time you get a custom XStream (custom driver is not related to this bug, the bug can still be reproduced after you remove the custom driver).
5. Write in the back

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.