JAXB Tip: One Line of Code to Marshall and Unmarshall XML
Join the DZone community and get the full member experience.Join For Free
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);
return (ClassToConvert)JAXB.unmarshal(xmlInputStream, ObjectToConvert.class);
JAXBContext context = JAXBContext.newInstance(objectInstanceToConvert.getClass());
Marshaller m = jc.createMarshaller();
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.
Opinions expressed by DZone contributors are their own.