XStream Convert XML, JSON

Source: Internet
Author: User

I. INTRODUCTION

XStream can easily convert Java objects and XML documents to each other, modify a specific attribute and node name, XStream provide annotation annotations,

You can complete the description of XML nodes and attributes in JavaBean, and support the conversion of JSON, just provide the relevant jsondriver to complete the conversion

Official website: http://xstream.codehaus.org/tutorial.html


Two. Preparatory work

1. Environment Readiness:

JAR file:

Https://nexus.codehaus.org/content/repositories/releases/com/thoughtworks/xstream/xstream-distribution/1.3.1/ Xstream-distribution-1.3.1-bin.zip

Code structure diagram:



2. JUnit Test Code:

public class xstreamtest {private XStream xstream;private objectoutputstream out;private objectinputstream in;private Student student;/** * Initialize Resource preparation */@Beforepublic void init () {try {XStream = new XStream (new Domdriver ())} catch (Exception e) {E.PR Intstacktrace ();} Student = new Student (), student.setaddress ("China"), Student.setemail ("[email protected]"); Student.setid (1); Student.setname ("Jack"); Birthday Birthday = new Birthday (); Birthday.setbirthday ("2010-11-22"); Student.setbirthday (birthday);} /** * Releases the object resource */@Afterpublic void Destory () {XStream = Null;student = null;try {if (out! = null) {Out.flush (); Out.close ();} if (in = null) {In.close ();}} catch (IOException e) {e.printstacktrace ();} System.GC ();} /** * Print string */public final void print (string string) {System.out.println (string);} /** * Highlight string */public final void HighLight (string string) {System.err.println (string);} 

3. Required entity classes:

(1) Student:

public class Student {private int id;private string Name;private string email;private string address;private Birthday Birt hday;//getter and Setterpublic String toString () {return this.name + "#" + this.id + "#" + this.address + "#" + This.birt Hday + "#" + This.email;}}


(2) Birthday

public class Birthday {private String birthday;public Birthday () {}public Birthday (String Birthday) {this.birthday = Birth Day;} Public String Getbirthday () {return birthday;} public void Setbirthday (String birthday) {this.birthday = birthday;}}

Three Java objects to XML

1. Turn the JavaBean into an XML document:

/**  * Java object is converted to XML */@Testpublic void Writebean2xml () {try {highLight ("====== Bean-and XML ======");p rint ("<!-- No renaming of XML--");p Rint (Xstream.toxml (student));p rint (" <!--renamed XML--");//class rename Xstream.alias (" Student ", Student.class); Xstream.alias ("Birthday", Birthday.class), Xstream.aliasfield ("Birthday", Student.class, "Birthday"); Xstream.aliasfield ("Birthday", Birthday.class, "Birthday");//Property Rename Xstream.aliasfield ("Mail", Student.class, "email");// Kaneshige named Xstream.aliaspackage ("ZDP", "Com.zdp.domain");p rint (Xstream.toxml (Student));} catch (Exception e) {e.printstacktrace ();}}


Operation Result:

====== Bean, XML ======<!--no renamed XML--><com.zdp.domain.student>  <id>1</id>  <name>jack</name>  <email>[email protected]</email>  <address>china</ address>  <birthday>    <birthday>2010-11-22</birthday>  </birthday></ com.zdp.domain.student><!--renamed XML--><student>  <id>1</id>  <name>jack </name>  < mail >[email protected]</mail >  <address>china</address>  < Birthdays >    < birthday >2010-11-22</Birthday >  </birthday ></student>

The first document is a document that has not been modified or renamed and is output as-is.

The classes, properties, and packages of the second document have been renamed.


2. Turn the list collection into an XML document:

/** * Convert List collection to XML object */@Testpublic void Writelist2xml () {try {//Modify element name Highlight ("====== list-to-XML ======"); XStream . Alias ("Beans", Listbean.class), Xstream.alias ("Student", Student.class); Listbean Listbean = new Listbean () Listbean.setname ("This is a List Collection"); list<object> list = new arraylist<object> ();//reference Javabeanlist.add (student); List.add (student); List.add (Listbean); Reference Listbean, parent element Student = new Student (); Student.setaddress ("China"); Student.setemail ("[email protected]"); Student.setid (2); Student.setname ("Tom"); Birthday Birthday = new Birthday ("2010-11-22"); Student.setbirthday (birthday); List.add (student); Listbean.setlist (list),//Set empty elements in Listbean, i.e. do not display the collection element label// Xstream.addimplicitcollection (Listbean.class, "list");//Set Reference Model Xstream.setmode (xstream.id_references); ID reference//xstream.setmode (xstream.no_references); Do not refer to//xstream.setmode (xstream.xpath_absolute_references); The absolute path reference//property of the element that sets the name to the parent class (Student) xstreAm.useattributefor (Student.class, "name"); Xstream.useattributefor (Birthday.class, "Birthday");//Modify the properties of the Namexstream.aliasattribute ("name", "name"); Xstream.aliasfield ("Birthday", Birthday.class, "Birthday");p rint (Xstream.toxml (Listbean));} catch (Exception e) {e.printstacktrace ();}}


Operation Result:

====== List---XML ======<beans id= "1" >  <name>this is a list collection</name>  <list ID = "2" >    <student id= "3" name = "Jack" >      <id>1</id>      <email>[email protected]</ email>      <address>china</address>      <birthday id= "4" birthday = "2010-11-22"/>    </student >    <student reference= "3"/>    <student id= "5" name = "Tom" >      <id>2</id>      < Email>[email protected]</email>      <address>china</address>      <birthday id= "6" birthday = " 2010-11-22 "/>    </student>  </list></beans>







XStream Convert XML, JSON

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.