Marshalling / Unmarshalling nulos en 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>y 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 debe configurarse para 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.

Pensé en usar @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 y 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).

preguntado el 08 de noviembre de 11 a las 15:11

Hmm, wouldn't an XMlAdapter for the Option class together with nillable = true on the annotations suffice? -

@forty-two: essentially, yes, but JAXB prefers to use xsi:nil for null elements instead of omitting them from the document. I'm not sure how you can convince JAXB to completely exclude an element... -

Note that a similar issue arises with empty collection vs. no collection at all: stackoverflow.com/questions/2250504/… -

@forty-two: The problem with using XmlAdapter is that I believe you have to annotate each field with @XmlJavaTypeAdapter. I have hundreds of fields in my server models. -

1 Respuestas

Siempre puede configurar el 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.

Espero que esto ayude,

respondido 08 nov., 11:20

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.