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 */@XmlRootElementpublic class Jaxbutil {/** * JavaBean convert to XML * * @param obj * @param encoding * @return */public static String converttoxml (Object obj) {TR Y {Jaxbcontext context = Jaxbcontext.newinstance (Obj.getclass ()); Marshaller Marshaller = Context.createmarshaller (); Marshaller.setproperty (marshaller.jaxb_encoding, "GBK"); Marshaller.setproperty (Marshaller.jaXb_fragment, True); Bytearrayoutputstream BAOs = new Bytearrayoutputstream (); Note JDK version xmloutputfactory xmloutputfactory = Xmloutputfactory.newinstance (); Xmlstreamwriter xmlstreamwriter = xmloutputfactory. Createxmlstreamwriter (BAOs, (String) marshaller . GetProperty (marshaller.jaxb_encoding)); Xmlstreamwriter.writestartdocument (String) Marshaller.getproperty (marshaller.jaxb_encoding), "1.0"); Marshaller.marshal (obj, xmlstreamwriter); Xmlstreamwriter.writeenddocument (); Xmlstreamwriter.close (); return new String (baos.tostring ("GBK")); } catch (Exception e) {//TODO auto-generated catch block E.printstacktrace (); } return null; }/** * XML is 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 (new StringReader (XML)); } catch (Exception e) {e.printstacktrace (); } return t; }}
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:
Import Javax.xml.bind.annotation.xmlaccesstype;import Javax.xml.bind.annotation.xmlaccessortype;import Javax.xml.bind.annotation.xmlelement;import Javax.xml.bind.annotation.xmlrootelement;import Javax.xml.bind.annotation.XmlType; @XmlAccessorType (Xmlaccesstype.field)//represents the use of private non-static fields in this class as serialized properties or elements of XML , the corresponding property uses the Get, set method. @XmlRootElement (name= "ROOT") @XmlType (proporder={"code", "Name", "Age"})//xml format data is displayed in the same order as the defined variable, Instead of @xmlelement in Namepublic class Mysocket {@XmlElement (name= "Code", required=true)//define the data displayed in the XML private String Code ; @XmlElement (name= "name", required=true) private String name; @XmlElement (name= "age", required=true) private String age; Public String GetCode () {return code; } public String GetName () {return name; } public String Getage () {return age; } public void Setcode (String code) {this.code = code; } public void SetName (String name) {this.name = name; } public void Setage (StrinG age) {this.age = age; } public String toString () {return this.name+ "," +this.age+ "," +this.code; }}
2) Set up the test class:
public class Test {public static void Main (string[] args) { objecttoxml (); } public static void Objecttoxml () { mysocket mysocket = new Mysocket (); Mysocket.setname ("Zhang San"); Mysocket.setcode ("00012"); Mysocket.setage ("+"); 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 () { String xml = "<?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 class Listsocket {@XmlElement (name= "name", required=true) private String name; @XmlElement (name= "age", required=true) private String age; @XmlElementWrapper (name= "ROWS")//@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) private list<book> books; Public String GetName () {return name; } public String Getage () {return age; } public list<book> Getbooks () {return books; } public void SetName (String name) {this.name = name; public void Setage (String age) {this.age = age; } public void Setbooks (List<book> books) {this.books = books; Public String toString () {String result = ""; Result=this.age+ "," +this.name+ ", set of data:"; for (book book:books) {Result+=book.getAuthor () +book.gettime () +book.getbookname (); } return result; }}
@XmlAccessorType (Xmlaccesstype.field) @XmlType (proporder={"BookName", "Time", "author"}) public class book { @ XmlElement (name= "BookName") private String bookname; @XmlElement (name= "Time") private String time; @XmlElement (name= "Author") private String Author; Public String Getbookname () { return bookname; } Public String GetTime () { return time; } Public String Getauthor () { return author; } public void Setbookname (String bookname) { this.bookname = bookname; } public void SetTime (String time) { this.time = time; } public void Setauthor (String author) { this.author = author; }}
3.2) Set up the test class:
public class Listsockettest {public static void main (string[] args) {objecttoxml (); Xmltoobject (); } public static void Objecttoxml () {Listsocket listsocket = new Listsocket (); Listsocket.setname ("Zhang San"); Listsocket.setage ("26"); list<book> books = new Arraylist<book> (); Book Book1 = new book (); Book1.setauthor ("author 1"); Book1.settime ("2014-12-28"); Book1.setbookname ("How to use JAXB"); Book book2= new book (); 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 void Xmltoobject () {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