JAXB mapping null-lists to empty collections?
Asked Answered
C

2

8

I have a webservice soap service that takes an object with an optional list as xml parameter:

@XmlElement(required = false)
private List<String> list;

public List<String> getList() { return list; }

Is it possible to tell JAXB to always return/use an empty collection instead of a null list if the list tag is not provided by the client?

Or will I always have to define a lazy getter on the server side for list that should never be null (I'd prefer this to be always the case)?

public List<String> getList() {
    if (list == null) {
        list = new ArrayList<String>();
    }
    return list;
}
Chagrin answered 25/8, 2014 at 9:56 Comment(0)
S
14

If you want the absence of the collection from the XML to correspond to an empty List in the Java object you just need to do the following.

@XmlElement(required = false)
private List<String> list = new ArrayList<String>();

This will marshal the same as if the field was null. There is only a difference in how a null and empty List is marshalled when the @XmlElementWrapper annotation is used.

Sabadell answered 25/8, 2014 at 10:26 Comment(1)
Update: 'required = false' is now the default when using @XmlElement.Erund
T
3

If you want the empty tag to be present, then either initialize with in getter as it is shown by you.

or

@XmlElement(required = false)
private List<String> list = new ArrayList<>();

So that the tag would be present.

Tui answered 25/8, 2014 at 10:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.