Simple way to marshall POJOs using JAXB

JAXB is a specification for marshalling and unmarshalling java objects to and from XML. The normal way (i.e. most commonly documented) to use it is to annotate your Java object. The annotations give you a lot of control, but even if you’re happy with the default settings, you still need to at least provide the @XMLRootElement annotation to make your class visible to JAXB, like so:

package jaxbtest;

import javax.xml.bind.annotation.XmlRootElement;

public class ServiceDTO {
	public MyDomainClass mdc;
    public ServiceDTO() {}
    public ServiceDTO(MyDomainClass mdc) {
    	this.mdc = mdc;

OK, this isn’t a real DTO. The next step would be to copy all the required data from the domain class into fields of the DTO. But it will serve our purpose for the moment.

To marshal ServiceDTO to XML, we can then do this:

    	MyDomainClass mdc = new MyDomainClass();

    	JAXBContext jc = JAXBContext.newInstance(ServiceDTO.class);
    	Marshaller marshaller = jc.createMarshaller();
    	marshaller.marshal(new ServiceDTO(mdc), System.out);

What if you can’t or don’t want to add JAXB annotations to your domain? See this very helpful post by the very helpful Blaise Doughan. You can still get fine-grained control over marshalling and unmarshalling by using Moxy to external JAXB configuration.

There is another way, though. In the java doc for JAXBContext, we find this intriguing statement:

Not only the new context will recognize all the classes specified, but it will also recognize any classes that are directly/indirectly referenced statically from the specified classes

That means that, given the above code, we can also marshal the domain object directly, like this:

marshaller.marshal(mdc, System.out);

As long as your class is referenced by an annotated class, it’s fair game for the marshaller.

I haven’t seen this technique mentioned at all in my research, so I presume there are some fundamental limitations to it. If you know of any, please let me know in the comments.

3 thoughts on “Simple way to marshall POJOs using JAXB

  1. Hi

    Thanks for the article. There is also another way to do marshal or unmarshal directly using JAXB static class like the following. Only prerequisite needed is a empty constructor for the class else exception raised.

    import javax.xml.bind.JAXB;
    JAXB.marshal(yourclass, System.out);

    import javax.xml.bind.JAXB;
    YourClass Object = (YourClass) JAXB.unmarshal(xmlString, YourClass.class)

    Note :
    1) import needed
    2) typecast needed

    Thanks again

    Siva K

  2. Yes. YourClass do not have to be annotated for most of the simple structures. For HashMaps and complex structures you need annotations for xmlType objects.


Leave a Reply

Your email address will not be published. Required fields are marked *