How do I have JAXB preserve nulls when receiving a JSON sting that contains a null or “” value.
String:{"id":null,"fname":"John","region":""}
returns Object:
Person {
Integer id = 0
String fname = "John"
Region regions = 0 }
I would like it to return null instead of 0
Here is what I have so far:
@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {
private JAXBContext context;
private Class<?>[] types = {Person.class};
public JAXBContextResolver() throws Exception {
this.context = new JSONJAXBContext(JSONConfiguration.natural().build(), types);
}
public JAXBContext getContext(Class<?> objectType) {
for (Class<?> c : types) {
if (c.equals(objectType)) {
return context;
}
}
return null;
}
}
Person.class is annotated with @XmlRootElement I’ve tried looking into Jackson annotations but have had no success.
Note: I’m the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
Below is an example of how this can be done with MOXy.
Person
MOXy will unmarshal the
Personobject as you want without specifying any metadata. To have the output JSON contain null values, you can use the@XmlElement(nillable=true)annotation (see Binding to JSON & XML – Handling Null).jaxb.properties
To specify MOXy as your JAXB (JSR-222) provider you need to add a file called
jaxb.propertiesin the same package as your domain classes with the following entry (see Specifying EclipseLink MOXy as Your JAXB Provider).Demo
Output
Using MOXy in a JAX-RS Application
For an example of using MOXy in a JAX-RS application see: