Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB mapping null-lists to empty collections?

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;
}
like image 388
membersound Avatar asked Aug 25 '14 09:08

membersound


2 Answers

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.

  • http://blog.bdoughan.com/2012/12/jaxb-representing-null-and-empty.html
like image 107
bdoughan Avatar answered Nov 10 '22 06:11

bdoughan


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.

like image 41
Vinay Veluri Avatar answered Nov 10 '22 08:11

Vinay Veluri