Java Socket message Communication (iii) conversion between Java objects and XML format files

Source: Internet
Author: User

The first two sections are about socket server, client building and packet encapsulation. Let's talk about the conversion between Java objects and XML format files today.

In the previous section we listed a message format, which we can actually understand as a string. But we can't write strings every time, so it's going to be crazy. Since it is object-oriented programming, there is certainly a good way to solve this problem. We use the Jaxbcontext tool.

Package Cn.com.egj.entity.shortcuttransfer.test;import Java.io.bufferedreader;import Java.io.bytearrayinputstream;import Java.io.bytearrayoutputstream;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.io.stringreader;import Java.net.urlencoder;import Javax.xml.bind.jaxbcontext;import Javax.xml.bind.jaxbexception;import Javax.xml.bind.marshaller;import Javax.xml.bind.unmarshaller;import Javax.xml.bind.annotation.xmlrootelement;import Javax.xml.stream.xmloutputfactory;import Javax.xml.stream.XMLStreamWriter;/** * Jaxb2 Tool class*/@XmlRootElement Public classJaxbutil {/** * JavaBean converted to XML * * @param obj * @param encoding * @return*/     Public StaticString converttoxml (Object obj) {Try{Jaxbcontext Context=jaxbcontext.newinstance (Obj.getclass ()); Marshaller Marshaller=Context.createmarshaller (); Marshaller.setproperty (marshaller.jaxb_encoding,"GBK"); Marshaller.setproperty (Marshaller.jaxb_fragment,true); Bytearrayoutputstream BAOs=NewBytearrayoutputstream (); //Note JDK versionXmloutputfactory xmloutputfactory =xmloutputfactory.newinstance (); Xmlstreamwriter Xmlstreamwriter=xmloutputfactory. Createxmlstreamwriter (BAOs, (String) marshaller. Getp            Roperty (marshaller.jaxb_encoding));                    Xmlstreamwriter.writestartdocument (String) Marshaller.getproperty (marshaller.jaxb_encoding), "1.0");            Marshaller.marshal (obj, xmlstreamwriter);            Xmlstreamwriter.writeenddocument ();            Xmlstreamwriter.close (); return NewString (Baos.tostring ("GBK")); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        return NULL; }    /** * XML converted to JavaBean * * @param XML * @param c * @return*/@SuppressWarnings ("unchecked")     Public Static<T> T Converytojavabean (String XML, class<t>c) {T T=NULL; Try{Jaxbcontext Context=jaxbcontext.newinstance (c); Unmarshaller Unmarshaller=Context.createunmarshaller (); T= (T) Unmarshaller.unmarshal (NewStringReader (XML)); } Catch(Exception e) {e.printstacktrace (); }        returnT; }}

The above two methods can convert Java object XML files to one another.

Next we'll see how to use it.

1) First we want to create a class that needs to be converted:

ImportJavax.xml.bind.annotation.XmlAccessType;ImportJavax.xml.bind.annotation.XmlAccessorType;Importjavax.xml.bind.annotation.XmlElement;Importjavax.xml.bind.annotation.XmlRootElement;ImportJavax.xml.bind.annotation.XmlType, @XmlAccessorType (Xmlaccesstype.field)//represents a property or element that uses the private non-static field in this class as the serialized attribute of XML, and the corresponding property uses the Get, set method. @XmlRootElement (name= "ROOT") @XmlType (Proporder={"Code", "Name", "Age"})//The order in which the XML format data is displayed is the same as the defined variable, not the name in the @xmlelement Public classmysocket {@XmlElement (name= "Code", required=true)//define the data displayed in the XML    PrivateString Code; @XmlElement (Name= "Name", required=true)    PrivateString name; @XmlElement (Name= "Age", required=true)    PrivateString age;  PublicString GetCode () {returnCode; }     PublicString GetName () {returnname; }     PublicString getage () {returnAge ; }     Public voidSetcode (String code) { This. Code =Code; }     Public voidsetName (String name) { This. Name =name; }     Public voidsetage (String age) { This. Age =Age ; }         PublicString toString () {return  This. name+ "," + This. age+ "," + This. Code; }}

2) Set up the test class:

 Public classTest { Public Static voidMain (string[] args) {objecttoxml (); }         Public Static  voidObjecttoxml () {mysocket mysocket=NewMysocket (); Mysocket.setname ("Zhang San"); Mysocket.setcode ("00012"); Mysocket.setage ("25"); String XML=Jaxbutil.converttoxml (mysocket);    SYSTEM.OUT.PRINTLN (XML); }    }

Run the test class and we'll see the console output: <?xml version= "1.0" encoding= "GBK"?><root><code>00012</code><age> 25</age></root>

For object to XML, we set up a test method:

 Public Static void xmltoobjetct () {        = "<?xml version=\" 1.0\ "encoding=\" gbk\ "? ><root><code>00011</ code><name> John Doe </Name><Age>26</Age></ROOT> ";        Mysocket mysocket= Jaxbutil.converytojavabean (XML, Mysocket.  Class);        System.out.println (Mysocket.tostring ());    }

Run the test class and we'll see the console output: John Doe, 26,00011

3) Sometimes there are collections in our Java objects, and we do this as follows:

3.1) First we set up the object of the bag collection:

@XmlAccessorType (Xmlaccesstype.field) @XmlRootElement (name= "ROOT") @XmlType (Proporder={"Name", "Age", "books"}) Public classListsocket {@XmlElement (name= "Name", required=true)    PrivateString name; @XmlElement (Name= "Age", required=true)    PrivateString age; @XmlElementWrapper (Name= "ROWS")//the @XmlElementWrapper annotation represents a wrapper element that generates a wrapper XML representation. This element is primarily used to generate wrapper XML elements for a wrapper collection@XmlElement (name= "LIST", required=true)    PrivateList<book>Books;  PublicString GetName () {returnname; }     PublicString getage () {returnAge ; }     PublicList<book>Getbooks () {returnBooks; }     Public voidsetName (String name) { This. Name =name; }     Public voidsetage (String age) { This. Age =Age ; }     Public voidSetbooks (list<book>Books) {         This. Books =Books; }         Publicstring toString () {string result= ""; Result= This. age+ "," + This. name+ ", Collection of data:";  for(book book:books) {result+=book.getauthor () +book.gettime () +Book.getbookname (); }        returnresult; }}

@XmlAccessorType (Xmlaccesstype.field) @XmlType (Proporder={"BookName", "Time", "author"}) Public classBook {@XmlElement (name= "BookName")    PrivateString BookName; @XmlElement (Name= "Time")    PrivateString time; @XmlElement (Name= "Author")    PrivateString author;  PublicString Getbookname () {returnBookName; }     PublicString GetTime () {returnTime ; }     PublicString Getauthor () {returnauthor; }     Public voidsetbookname (String bookname) { This. BookName =BookName; }     Public voidsettime (String time) { This. Time =Time ; }     Public voidSetauthor (String author) { This. Author =author; }}

3.2) Set up the test class:

 Public classListsockettest { Public Static voidMain (string[] args) {objecttoxml ();    Xmltoobject (); }         Public Static voidObjecttoxml () {listsocket Listsocket=NewListsocket (); Listsocket.setname ("Zhang San"); Listsocket.setage ("26"); List<Book> books =NewArraylist<book>(); Book Book1=NewBook (); Book1.setauthor ("Author 1"); Book1.settime ("2014-12-28"); Book1.setbookname ("How to use JAXB"); Book Book2=NewBook (); Book2.setauthor ("Author 2"); Book2.settime ("2014-06-06"); Book2.setbookname ("How to use SOCKET");        Books.add (BOOK1);        Books.add (BOOK2);        Listsocket.setbooks (books); String XML=Jaxbutil.converttoxml (Listsocket);    SYSTEM.OUT.PRINTLN (XML); }         Public Static voidXmltoobject () {String XML= "<?xml version=\" 1.0\ "encoding=\" Gbk\ "?><root><name> Zhang San </Name><Age>26</Age> <ROWS><LIST> "
+ "<bookname>how to use jaxb</bookname><time>2014-12-28</time><author> author 1</author > "
+ "</list><list><bookname>how to use socket</bookname><time>2014-06-06</time> <Author> author 2</author></list></rows></root> "; Listsocket Listsocket= Jaxbutil.converytojavabean (XML, Listsocket.class); System.out.println (Listsocket); }

Running the main function, we can see the transformed XML object and the Class object. The use is so simple ^_^!!!

Java Socket message Communication (iii) conversion between Java objects and XML format files

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.