Jeff Sexton

Thursday, February 12, 2009

Marshalling and Unmarshalling Without a @XmlRootElement

Red is the dominant color!Image by swisscan via Flickr
Netbeans has a handy feature off on the palette on the right (usually) of the code editor, where you can drag a marshal or unmarshal object into your Java code and it will generate marshal/unmarshal code for the XML or JAXB object of your choice.

It is interesting that sometimes, although it does not complain when generating these code fragments, there will occur an error at runtime stating that an object has no @XmlRootElement.

@XmlRootElement annotations are not always created in JAXB objects. Here is a nice explanation of why that is:

http://weblogs.java.net/blog/kohsuke/archive/2006/03/why_does_jaxb_p.html

The subject of this post is not why this happens, but rather how to deal with these objects when you don't want to use inline complex types.

Here's a sample marshal method more or less as generated by the wizard of Netbeans:

private String jaxbMarshalToString(MyType jaxbObj) throws javax.xml.bind.JAXBException, java.io.IOException {
java.io.StringWriter sw = new java.io.StringWriter();
javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(jaxbObj.getClass().getPackage().getName());
javax.xml.bind.Marshaller marshaller = jaxbCtx.createMarshaller();
marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8");
//NOI18N
marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(jaxbObj, sw);
sw.close();
return sw.toString();
}
Here is an unmarshal method for the same object:

private MyType jaxbUnmarshalFromString(String str) throws javax.xml.bind.JAXBException {
MsgQMessageType ret = null;
javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(MyType.class);
javax.xml.bind.Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();
ret = (MyType) unmarshaller.unmarshal(new java.io.StringReader(str));
//NOI18N
return ret;
}
This object has "Type" appended to its name. That is a sign that this is a container rather than the JAXB representation of the XSD itself. These methods fail at runtime because the object jaxbObj includes no root annotation.

Here are these two methods changed so they work. In the first method, we create a new JAXBElement (so it will have a root element) and marshal that. In the second method, we unmarshal to a JAXBElement, and return that object's getValue(), cast to our desired type. Also in the unmarshal code, the context is created using getPackage().getName() rather than just the class.

private String jaxbMarshalToString(MyType jaxbObj) throws javax.xml.bind.JAXBException, java.io.IOException {
java.io.StringWriter sw = new java.io.StringWriter();
javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(jaxbObj.getClass().getPackage().getName());
javax.xml.bind.Marshaller marshaller = jaxbCtx.createMarshaller();
marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "UTF-8");
//NOI18N
marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(new JAXBElement(
new QName("http://www.namespace.com/schema/My", "My"),
MyType.class,
jaxbObj), sw);
sw.close();
return sw.toString();
}

private MyType jaxbUnmarshalFromString(String str) throws javax.xml.bind.JAXBException {
JAXBElement ret = null;
javax.xml.bind.JAXBContext jaxbCtx = javax.xml.bind.JAXBContext.newInstance(MyType.class.getPackage().getName());
javax.xml.bind.Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();
ret = (JAXBElement) unmarshaller.unmarshal(new java.io.StringReader(str));
//NOI18N
return (
MyType)ret.getValue();
}




Reblog this post [with Zemanta]










Post a Comment
3D modeling Advertising Air Canada Airline Alfa Romeo Spider Touring Gran Sport Analog signal Android Anomalies and Alternative Science Apache Apollo Astoria Augmented reality Aurora Famous Fighters auto-awesome Automobile Autos Barack Obama Batman Beards Beer Bell System Berkshire Hathaway Bigfoot Bird Toys Birds Blogger Books Build Management Business and Economy Business Process Execution Language Byte-order mark Canadian Carrot Cats Christmas Civil Defense CNN Cockatiels Collections Crows Dear Jane Debian Diabetes Digital Living Network Alliance Digital television Disney Doll House Dow Jones Industrial Average Duesenburg SJ Roadster Durham University E-mail address ebauche Economics EJB Energy development Enterprise JavaBean ESP Facebook Fedora Filesharing Finance Ford Fossil fuel Garfield James Abram Garfield Minus Garfield Glassfish Global warming Golden Arches Goofy Google Google Buzz Google Docs Google Lively Google Photos Google Reader Google Wave Google+ Greenhouse gas Half-Life 2 Helbros High-definition television History Hybrid electric vehicle IBM Inner city Instagram Insulin Investing Irony J.C. Penny Jane Austen Java Java Architecture for XML Binding JDBC Jeff's! Jim Davis joe the plumber John McCain Karma Kay Thompson Kermit the Frog Kids and Teens LA Auto Show Larry King Laser Logging Lowry Sexton Mark Cuban Market trends McDonald Meier and Frank Microsoft Microsoft Windows Models Monkey monsters Moon MOUNT HOOD Music Music industry Muxtape MySQL NetBeans Netflix Nintendo Nissan Cube Norm Coleman Nuclear fallout Nuclear warfare Office Depot Open ESB Oracle Corporation Pacific Ocean Packard Boattail Pearl District Pearl District Portland Oregon Philip K Dick photography PlayStation 3 Pocher Pokémon HeartGold and SoulSilver Politics Portal Portland Portland Development Commission Presidents Pride and Prejudice Programming Projects Radio Recording Industry Association of America Renewable energy RIAA Robot Chicken Rock-paper-scissors Sarcasm Science fiction film Serbia Service-oriented architecture Shopping Slide Rule Social Security Social Studies Society6 Spirit of St. Louis SQL Stanford Hospital Star Wars Starbucks Stock market Strip search Sun Microsystems T-Mobile TechCrunch Technical ThinkGeek Toaster Total Recall Transportation Security Administration Unicode United States United States Department of Homeland Security Universal Plug and Play Unknown Primates Vegetable garden Video game Vintage Images Vintage Vintage! Virtual world Volvo C70 Wall Street Warren Buffett watches We Can Remember It for You Wholesale Web service Web Services Description Language Wii Windows 7 Windows Phone 7 Windows Vista Windows XP X-Files X-ray vision XML XML Schema YouTube Yugo Zima