Using JAXB to implement a mutual conversion instance of Java objects and XML strings

Source: Internet
Author: User

Test class:

Package com.yanek.test;
Import java.util.ArrayList;

Import java.util.List;


Import Com.yanek.test.JaxbUtil.CollectionWrapper; public class Test {/** * @param args */public static void main (string[] args) {//Create Java Objects Hotel Hotel=ne
		W Hotel ();
		Hotel.setid (1);

		Hotel.setname ("name1");
		Roomtypevo t1=new Roomtypevo ();
		T1.setprice ("20");
		T1.settypeid (1);
		
		T1.settypename ("typename1");
		Roomtypevo t2=new Roomtypevo ();
		T2.setprice ("30");
		T2.settypeid (2);
		

		T2.settypename ("typename2");
		List<roomtypevo> roomtypevos=new arraylist<roomtypevo> ();
		Roomtypevos.add (t1);
		Roomtypevos.add (T2);

		
		Hotel.setroomtypevos (Roomtypevos);
		Converts a Java object to an XML string jaxbutil Requestbinder = new Jaxbutil (Hotel.class, Collectionwrapper.class);
		String retxml = Requestbinder.toxml (hotel, "Utf-8");
		
		SYSTEM.OUT.PRINTLN ("xml:" +retxml);
		Converts an XML string to a Java object jaxbutil Resultbinder = new Jaxbutil (Hotel.class, Collectionwrapper.class); Hotel HotelOBJ = Resultbinder.fromxml (retxml);
		System.out.println ("Hotelid:" +hotelobj.getid ());
		System.out.println ("Hotelname:" +hotelobj.getname ());
			For (Roomtypevo roomTypeVO:hotelObj.getRoomTypeVOs ()) {System.out.println ("typeID:" +roomtypevo.gettypeid ());
		System.out.println ("Typename:" +roomtypevo.gettypename ());
 }

		
	}

}


The output is as follows:

Xml:<?xml version= "1.0" encoding= "Utf-8" standalone= "yes"?> 


Related classes:

Package com.yanek.test;

Import java.util.List;
Import Javax.xml.bind.annotation.XmlAttribute;
Import javax.xml.bind.annotation.XmlElement;
Import Javax.xml.bind.annotation.XmlElementWrapper;

Import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement (name = "Hotel") public class Hotel {@XmlElementWrapper (name = "Roomtypevos") @XmlElement (name = "Roomty")
	Pevo ") Public list<roomtypevo> Getroomtypevos () {return roomtypevos;
	public void Setroomtypevos (list<roomtypevo> roomtypevos) {roomtypevos = Roomtypevos;
	
	Private list<roomtypevo> Roomtypevos;
	@XmlElement (name = "id") @XmlAttribute (name = "id") public int getId () {return id;
	The public void setId (int id) {this.id = ID;
	@XmlElement (name = "name") public String GetName () {return name;
	public void SetName (String name) {this.name = name;
	} private int id;
	

private String name;

} package com.yanek.test;
Import Javax.xml.bind.annotation.XmlAttribute; Import JAVAx.xml.bind.annotation.XmlElement; public class Roomtypevo {///@XmlElement (name = "typeID") @XmlAttribute (name = ' typeid ') public int GetTypeId () {R
	Eturn typeID;
	The public void Settypeid (int typeid) {This.typeid = typeID;
	@XmlElement (name = "TypeName") public String Gettypename () {return typename;
	} public void Settypename (String typename) {this.typename = typename;
	@XmlElement (name = "Price") is public String GetPrice () {return price;
	public void Setprice (String price) {this.price = Price;
	} private int typeid;
	Private String TypeName;

Private String Price; }

JAXB Simple Tools class:

Package com.yanek.test;
Import Java.io.StringReader;
Import Java.io.StringWriter;

Import java.util.Collection;
Import Javax.xml.bind.JAXBContext;
Import javax.xml.bind.JAXBElement;
Import javax.xml.bind.JAXBException;
Import Javax.xml.bind.Marshaller;
Import Javax.xml.bind.Unmarshaller;
Import javax.xml.bind.annotation.XmlAnyElement;

Import Javax.xml.namespace.QName;

Import Org.apache.commons.lang.StringUtils;
 /** * uses Jaxb2.0 to implement Xml<->java object binder.
 * * Special support for the root object is a list of cases.
	* * @author/public class Jaxbutil {//Multithreading security context.

	Private Jaxbcontext Jaxbcontext;
	 /** * @param types * All types of root objects that need to be serialized.
		* * Public jaxbutil (CLASS&LT;?&GT; types) {try {Jaxbcontext = jaxbcontext.newinstance (types);
		catch (Jaxbexception e) {throw new RuntimeException (e);
	 }/** * Java object->xml.
			*/Public String toXml (Object root, String encoding) {try {StringWriter writer = new StringWriter (); Createmarshaller (encoding). MarShal (root, writer);
		return writer.tostring ();
		catch (Jaxbexception e) {throw new RuntimeException (e);
	 }/** * Java Object->xml, which specifically supports situations where root element is collection. */@SuppressWarnings ("unchecked") public String toXml (Collection root, String rootname, string encoding) {try {Co
			Llectionwrapper wrapper = new Collectionwrapper ();

			Wrapper.collection = root;  jaxbelement<collectionwrapper> wrapperelement = new jaxbelement<collectionwrapper> (new QName (RootName),

			Collectionwrapper.class, wrapper);
			StringWriter writer = new StringWriter ();

			Createmarshaller (encoding). Marshal (Wrapperelement, writer);
		return writer.tostring ();
		catch (Jaxbexception e) {throw new RuntimeException (e);
	 }/** * Xml->java Object. */@SuppressWarnings ("unchecked") public <T> T fromxml (String xml) {try {StringReader reader = new Stringre
			Ader (XML);
		Return (T) Createunmarshaller (). Unmarshal (reader); catch (jaxbexception e) {throw new RuntimeException (e);
	 }/** * Xml->java Object to support case sensitive or insensitive. */@SuppressWarnings ("unchecked") public <T> T fromxml (String xml, Boolean casesensitive) {try {string from
			XML = XML;
			if (!casesensitive) FromXml = Xml.tolowercase ();
			StringReader reader = new StringReader (fromxml);
		Return (T) Createunmarshaller (). Unmarshal (reader);
		catch (Jaxbexception e) {throw new RuntimeException (e);
	 }/** * Create Marshaller, set encoding (nullable). */Public Marshaller Createmarshaller (String encoding) {try {Marshaller Marshaller = Jaxbcontext.createmarshaller (

			);

			Marshaller.setproperty (Marshaller.jaxb_formatted_output, boolean.true);
			if (Stringutils.isnotblank (encoding)) {Marshaller.setproperty (marshaller.jaxb_encoding, encoding);
		return marshaller;
		catch (Jaxbexception e) {throw new RuntimeException (e);
	 }/** * Create Unmarshaller.
	*/Public Unmarshaller Createunmarshaller () {try {		return Jaxbcontext.createunmarshaller ();
		catch (Jaxbexception e) {throw new RuntimeException (e);
	 }/** * Encapsulates root Element is a collection case. */public static class Collectionwrapper {@SuppressWarnings ("unchecked") @XmlAnyElement protected Collection Colle
	ction;

 }
}




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.