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;
}
                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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With