Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jaxb marshalling skip empty elements

Tags:

java

jaxb

Using JAXB is it possible to ensure that null values are not marshalled as () empty elements. For instance

public class Contacts {
    @XmlElement(name = "Phone")
    protected List<Phone> phone;
    }

currently if one of the phone element is null i get

<contact>
         </phone>
         <phone>
                <areacode>919</areacode>
                <phonenumber>6785432</phonenumber>
         </phone>
    </contact>

i want the following output

<contact>
            <phone>
                   <areacode>919</areacode>
                   <phonenumber>6785432</phonenumber>
            </phone>
   </contact>
like image 320
amol ghonge Avatar asked Sep 18 '12 22:09

amol ghonge


1 Answers

Null values are not marshaled as empty element by default.
Only empty values are marshalled as empty element

In your example you are using collection with empty Phone object element. You have two elements in list: empty Phone (all fields are null) and Phone object with not null fields.
So,

public class Contacts {
    @XmlElement(name = "Phone")
    protected List<Phone> phone = Arrays.asList(new Phone[]{null, null, null});
}  

will be marshalled to

<contact/>  

but

public class Contacts {
    @XmlElement(name = "Phone")
    protected List<Phone> phone = Arrays.asList(new Phone[]{new Phone(), new Phone(), null});
}

will be marshalled to

<contact>   
    <Phone/>  
    <Phone/>  
</contact>
like image 113
Ilya Avatar answered Nov 09 '22 12:11

Ilya