I have several hand-written Java classes in a REST Server that uses JAXB to marshall/unmarshall from XML (JAX-RS).
I have implemented a small class hierarchy borrowed from Scala: Option<T>, Some<T>, and None<T> and would like to use these in my model to distinguish missing values from null values in the XML.
For example, in the following XML, the value phone_number is missing and the corresponding Java model field should be set to None:
<person>
<last_name>Jones</last_name>
<first_name>Abe</first_name>
</person>
class Person {
@XmlElement("last_name")
Option<String> lastName;
@XmlElement("first_name")
Option<String> firstName;
@XmlElement("phone_number")
Option<String> phoneNumber;
}
whereas in the this XML message, the phone_number should be set to new Some(null):
<person>
<last_name>Jones</last_name>
<first_name>Abe</first_name>
<phone_number></phone_number>
</person>
I realize that with this scheme, I cannot distinguish a zero-length String from a null String.
I thought of using @XmlJavaTypeAdapter, but I have many model classes and would rather use a “centralized” solution that works for all of the classes.
I believe that the correct solution involves using a MessageBodyWriter and MessageBodyReader, but I still want the built-in machinery to handle each of the classes; I’ll handle the individual fields (including String and Date).
You can always set the
Personclass attributes to default values.If you default
PhoneNumberto “None”, saving it to XML will give you the following tagIn any case, the PhoneNumber attribute will stay at “None” until you call a setter to set the phone number real value.
I hope this helps,