I'm using JAXB to serialize objects to XML. Now I realize that it will exclude natural null values from response but will not exclude null values from customized adapters. Below is my code.
package com.model;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class JAXBTest {
public static void main(String[] args) throws JAXBException {
JAXBContext jc = JAXBContext.newInstance(Thing.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Thing thing = new Thing();
thing.setName("popcorn ball");
thing.setAwesome(false);
marshaller.setAdapter(BooleanAdapter.class,new BooleanAdapter(true));
marshaller.marshal(thing, System.out);
}
@XmlRootElement
public static class Thing{
private String name;
private Boolean awesome;
private String empty;
public String getEmpty() {
return empty;
}
public void setEmpty(String empty) {
this.empty = empty;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setAwesome(Boolean awesome) {
this.awesome = awesome;
}
public Boolean isAwesome() {
return this.awesome;
}
}
public static class BooleanAdapter extends XmlAdapter<String, Boolean> {
boolean flag;
public BooleanAdapter(boolean flag){
this.flag = flag;
}
public Boolean unmarshal(String v) throws Exception {
return Boolean.TRUE.equals(v);
}
public String marshal(Boolean v) throws Exception {
if(flag){
if(v) {
return v.toString();
}
return null;
}else{
return v.toString();
}
}
}
}
packageinfo.java:
@XmlJavaTypeAdapter(value=JAXBTest.BooleanAdapter.class, type=Boolean.class)
package com.model;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
Output:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<thing>
<awesome/>
<name>popcorn ball</name>
</thing>
As you can see, even I return null in the Adapter, there is still an empty node in the response awesome/. The natural null field "private String empty" is perfectly ignored. So my question is, how to exclude these empty nodes from response?