Over a million developers have joined DZone.

JAXB Tip: One Line of Code to Marshall and Unmarshall XML

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

I wrote in a previous article how easy it is to translate Java object to/from XML, without adding exotic library dependencies to your project; recently I’ve going through the code of one of my colleague and I discovered that the 3 line necessary to marshal and un-marshal the XML can be shortened to a single line using the JAXB utility class:

JAXBContext context = JAXBContext.newInstance(ObjectToConvert.class);
Unmarshaller u = context.createUnmarshaller();
return (ObjectToConvert) u.unmarshal(xmlInputStream);

// becomes
return (ClassToConvert)JAXB.unmarshal(xmlInputStream, ObjectToConvert.class);

// and
JAXBContext context = JAXBContext.newInstance(objectInstanceToConvert.getClass());
Marshaller m = jc.createMarshaller();
m.marshal(objectInstanceToConvert, xmlOutputStream);

// becomes
JAXB.marshall(objectInstanceToConvert, xmlOutputStream)

Nice: one line of code to convert Java objects from/to XML. I didn’t notice this utility method in the JAXB library at first, so I was implementing those two methods in my code, more or less the same way. It’s always good to remove code.

From http://en.newinstance.it/2011/05/26/jaxb-tip-one-line-of-code-to-marshall-and-unmarshall-xml/

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}