A JAXB (JSR-222) will return an empty String "" as an empty element. You can set the address property for this to get the desired effect.
UPDATE # 1
I updated my question. Basically, the address element is NULL. Is this decision applicable to this?
You can use Marshal Event Callbacks to configure the address value.
import javax.xml.bind.Marshaller; import javax.xml.bind.annotation.*; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Customer { private String name; private String address; private void beforeMarshal(Marshaller marshaller) { if(null == address) { address = ""; } } private void afterMarshal(Marshaller marshaller) { if("".equals(address)) { address = null; } } }
UPDATE # 2
The only problem is that if I have 10 fields in the class, I will have to write if for all fields. Is there any other solution?
If you are using EclipseLink MOXy as a JAXB provider (I am the lead MOXy), then you can use the XmlAdapter for this use case.
XmlAdapter (StringAdapter)
package forum14691333; import javax.xml.bind.annotation.adapters.XmlAdapter; public class StringAdapter extends XmlAdapter<String, String> { @Override public String marshal(String string) throws Exception { if(null == string) { return ""; } return string; } @Override public String unmarshal(String string) throws Exception { if("".equals(string)) { return null; } return string; } }
package info
Then, if you specify it at the package level, it will apply to all displayed fields / properties of type String inside this package.
@XmlJavaTypeAdapter(value=StringAdapter.class, type=String.class) package forum14691333; import javax.xml.bind.annotation.adapters.*;
Additional Information
source share