DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • What Is Ant, Really?
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)
  • How to Convert XLS to XLSX in Java
  • Thread-Safety Pitfalls in XML Processing

Trending

  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  • How to Configure and Customize the Go SDK for Azure Cosmos DB
  • A Modern Stack for Building Scalable Systems
  1. DZone
  2. Coding
  3. Languages
  4. JAXB - Representing Null and Empty Collections

JAXB - Representing Null and Empty Collections

By 
Blaise Doughan user avatar
Blaise Doughan
·
Jan. 03, 13 · Interview
Likes (0)
Comment
Save
Tweet
Share
51.1K Views

Join the DZone community and get the full member experience.

Join For Free

In this post I will cover how to differentiate between null and empty collections in the XML representation with JAXB (JSR-222).

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 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>




XML Annotation Use case Element Trip (search engine) Property (programming) Java (programming language) POST (HTTP)

Published at DZone with permission of Blaise Doughan, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • What Is Ant, Really?
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)
  • How to Convert XLS to XLSX in Java
  • Thread-Safety Pitfalls in XML Processing

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: