I have a class that I would like to expose through a Jersey RESTful API. It looks similar to this:
@XmlRootElement
public class Data {
public String firstName;
public String lastName;
}
My problem is that these fields may be null, in which case the field is omitted from the JSON output. I would like all fields to be present regardless of their value. For example, if lastName is null, the JSON output will be:
{
"firstName" : "Oleksi"
}
instead of what I want:
{
"firstName" : "Oleksi",
"lastName" : null
}
I have a JAXBContextResolver (an implementation of ContextResolver) that looks like this:
@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {
// internal state
private final JAXBContext context;
private final Set<Class> types;
private final Class[] cTypes = { Data.class };
public JAXBContextResolver()
throws Exception {
types = new HashSet(Arrays.asList(cTypes));
context = new JSONJAXBContext(JSONConfiguration.natural().humanReadableFormatting(true).build(), cTypes);
}
@Override
public JAXBContext getContext(Class<?> objectType) {
return (types.contains(objectType)) ? context : null;
}
}
I’ve been trying to figure out how to get that desired output for a while, but I’ve had no luck. I’m open to trying other ContextResolvers/Serializers, but I haven’t been able to find one that works, so code examples would be nice.
For EclipseLink JAXB (MOXy)‘s JSON binding, the correct mapping would be the following. You could try it with your provider to see if it would work also:
For More Information
UPDATE 2
EclipseLink 2.4 includes
MOXyJsonProviderwhich is an implementation ofMessageBodyReader/MessageBodyWriterthat you can use directly to leverage MOXy’s JSON bindingUPDATE 1
The following
MessageBodyReader/MessageBodyWritermay work better for you: