About Blaise Doughan

Team lead for the TopLink/EclipseLink JAXB & SDO implementations, and the Oracle representative on those specifications.

JAXB – Representing Null and Empty Collections

Demo Code

The following demo code will be used for all the different versions of the Java model. It simply sets one collection to null, the second to an empty list, and the third to a populated list.
 
 
 
 
 
 

package package blog.xmlelementwrapper;

import java.util.ArrayList;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);

        Root root = new Root();

        root.nullCollection = null;

        root.emptyCollection = new ArrayList<String>();

        root.populatedCollection = new ArrayList<String>();
        root.populatedCollection.add('foo');
        root.populatedCollection.add('bar');

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }

}

Mapping #1 – Default

JAXB models do not require any annotations (see JAXB – No Annotations Required). First we will look at what the default behaviour is for collection properties.

package blog.xmlelementwrapper;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {

    List<String> nullCollection;

    List<String> emptyCollection;

    List<String> populatedCollection;

}

Examining the output we see that the output corresponding to the nullCollection and emptyCollection fields is the same. This means with the default mapping we can’t round trip the instance. For the unmarshal use case the value of the nullCollection and emptyCollection the value of the fields will be whatever the class initialized them to (null in this case).

<?xml version='1.0' encoding='UTF-8'?>
<root>
    <populatedCollection>foo</populatedCollection>
    <populatedCollection>bar</populatedCollection>
</root>

Mapping #2 – @XmlElementWrapper

The @XmlElementWrapper annotation is used to add a grouping element around the contents of a collection. In addition to changing the appearance of the XML representation it also allows us to distinguish between null and empty collections.

package blog.xmlelementwrapper;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {

    @XmlElementWrapper
    List<String> nullCollection;

    @XmlElementWrapper
    List<String> emptyCollection;

    @XmlElementWrapper
    List<String> populatedCollection;

}

The representation for the null collection remains the same, it is absent from the XML document. For an empty collection we see that only the grouping element is marshalled out. Since the representations for null and empty are different we can round trip this use case.

<?xml version='1.0' encoding='UTF-8'?>
<root>
    <emptyCollection/>
    <populatedCollection>
        <populatedCollection>foo</populatedCollection>
        <populatedCollection>bar</populatedCollection>
    </populatedCollection>
</root>

Mapping #3 – @XmlElementWrapper(nillable=true)

The nillable property on the @XmlElementWrapper annotation can be used to change the XML representation of null collections.

package blog.xmlelementwrapper;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {

    @XmlElementWrapper(nillable=true)
    List<String> nullCollection;

    @XmlElementWrapper(nillable=true)
    List<String> emptyCollection;

    @XmlElementWrapper(nillable=true)
    List<String> populatedCollection;

}

Now the grouping element is present for all three fields. The xsi:nil attribute is used to indicate that the nullCollection field was null. Like the previous mapping this one can be round tripped.

<?xml version='1.0' encoding='UTF-8'?>
<root>
    <nullCollection 
        xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
        xsi:nil='true'/>
    <emptyCollection/>
    <populatedCollection>
        <populatedCollection>foo</populatedCollection>
        <populatedCollection>bar</populatedCollection>
    </populatedCollection>
</root>

 

Reference: JAXB – Representing Null and Empty Collections from our JCG partner Blaise Doughan at the Java XML & JSON Binding blog.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


8 − four =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books