使用JAXB在Jersey RESTful API的JSON输出中包含null元素 [英] Including null elements in JSON output of Jersey RESTful API with JAXB
问题描述
我有一个类,我想通过Jersey RESTful API公开。它看起来类似于:
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;
}
我的问题是这些字段可能为空,在这种情况下字段是从JSON输出中省略。我希望所有领域都存在,无论它们的价值如何。例如,如果lastName为null,则JSON输出将为:
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"
}
而不是我想要的:
{
"firstName" : "Oleksi",
"lastName" : null
}
我有一个JAXBContextResolver(ContextResolver的实现),如下所示:
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;
}
}
我一直试图找出如何获得那个期望的输出一段时间,但我没有运气。我愿意尝试其他ContextResolvers / Serializers,但我找不到一个有效的代码示例,所以代码示例会很好。
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.
推荐答案
对于 EclipseLink JAXB(MOXy) 的JSON绑定,正确的映射如下。您可以尝试与您的提供商一起查看它是否也可以使用:
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:
@XmlRootElement
public class Data {
@XmlElement(nillable=true)
public String firstName;
@XmlElement(nillable=true)
public String lastName;
}
更多信息
- http://blog.bdoughan.com/2012/04/binding-to-json-xml-handling-null.html
- http://blog.bdoughan.com/2012/05/moxy-as-your-jax- rs-json-provider.html
- http://blog.bdoughan.com/2012/04/binding-to-json-xml-handling-null.html
- http://blog.bdoughan.com/2012/05/moxy-as-your-jax-rs-json-provider.html
更新2
EclipseLink 2.4包含 MOXyJsonProvider
这是 MessageBodyReader <的实现/ code> /
MessageBodyWriter
您可以直接使用MOXy的JSON绑定
EclipseLink 2.4 includes MOXyJsonProvider
which is an implementation of MessageBodyReader
/MessageBodyWriter
that you can use directly to leverage MOXy's JSON binding
- http://blog.bdoughan.com/2012/05/moxy-as-your-jax-rs-json-provider.html
更新1
关注 MessageBodyReader
/ MessageBodyWriter
可能更适合您:
The following MessageBodyReader
/MessageBodyWriter
may work better for you:
import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import javax.xml.transform.stream.StreamSource;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.ws.rs.ext.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
@Provider
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class MOXyJSONProvider implements
MessageBodyReader<Object>, MessageBodyWriter<Object>{
@Context
protected Providers providers;
public boolean isReadable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return true;
}
public Object readFrom(Class<Object> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
throws IOException, WebApplicationException {
try {
Class<?> domainClass = getDomainClass(genericType);
Unmarshaller u = getJAXBContext(domainClass, mediaType).createUnmarshaller();
u.setProperty("eclipselink.media-type", mediaType.toString());
u.setProperty("eclipselink.json.include-root", false);
return u.unmarshal(new StreamSource(entityStream), domainClass).getValue();
} catch(JAXBException jaxbException) {
throw new WebApplicationException(jaxbException);
}
}
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return true;
}
public void writeTo(Object object, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException,
WebApplicationException {
try {
Class<?> domainClass = getDomainClass(genericType);
Marshaller m = getJAXBContext(domainClass, mediaType).createMarshaller();
m.setProperty("eclipselink.media-type", mediaType.toString());
m.setProperty("eclipselink.json.include-root", false);
m.marshal(object, entityStream);
} catch(JAXBException jaxbException) {
throw new WebApplicationException(jaxbException);
}
}
public long getSize(Object t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return -1;
}
private JAXBContext getJAXBContext(Class<?> type, MediaType mediaType)
throws JAXBException {
ContextResolver<JAXBContext> resolver
= providers.getContextResolver(JAXBContext.class, mediaType);
JAXBContext jaxbContext;
if(null == resolver || null == (jaxbContext = resolver.getContext(type))) {
return JAXBContextFactory.createContext(new Class[] {type}, null);
} else {
return jaxbContext;
}
}
private Class<?> getDomainClass(Type genericType) {
if(genericType instanceof Class) {
return (Class<?>) genericType;
} else if(genericType instanceof ParameterizedType) {
return (Class<?>) ((ParameterizedType) genericType).getActualTypeArguments()[0];
} else {
return null;
}
}
}
这篇关于使用JAXB在Jersey RESTful API的JSON输出中包含null元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!