简体   繁体   中英

Marshalling/Unmarshalling nulls in JAXB

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 Person class attributes to default values. If you default PhoneNumber to "None", saving it to XML will give you the following tag

 <phone_number>None</phone_number>

In 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,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM