简体   繁体   English

使用JAXB在Jersey RESTful API的JSON输出中包含null元素

[英]Including null elements in JSON output of Jersey RESTful API with JAXB

I have a class that I would like to expose through a Jersey RESTful API. 我有一个类,我想通过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. 我的问题是这些字段可能为null,在这种情况下,字段从JSON输出中省略。 I would like all fields to be present regardless of their value. 我希望所有领域都存在,无论它们的价值如何。 For example, if lastName is null, the JSON output will be: 例如,如果lastName为null,则JSON输出将为:

{
   "firstName" : "Oleksi"
}

instead of what I want: 而不是我想要的:

{
   "firstName" : "Oleksi",
   "lastName" : null
}

I have a JAXBContextResolver (an implementation of ContextResolver) that looks like this: 我有一个JAXBContextResolver(ContextResolver的实现),如下所示:

@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. 我愿意尝试其他ContextResolvers / Serializers,但我找不到一个有效的代码示例,所以代码示例会很好。

For EclipseLink JAXB (MOXy) 's JSON binding, the correct mapping would be the following. 对于EclipseLink JAXB(MOXy)的JSON绑定,正确的映射如下。 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;
}

For More Information 欲获得更多信息


UPDATE 2 更新2

EclipseLink 2.4 includes MOXyJsonProvider which is an implementation of MessageBodyReader / MessageBodyWriter that you can use directly to leverage MOXy's JSON binding EclipseLink 2.4包含MOXyJsonProvider ,它是MessageBodyReader / MessageBodyWriter一个实现,您可以直接使用它来利用MOXy的JSON绑定

UPDATE 1 更新1

The following MessageBodyReader / MessageBodyWriter may work better for you: 以下MessageBodyReader / MessageBodyWriter可能更适合您:

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;
        }
    }

}

Java null is JavaScript's undefined. Java null是JavaScript未定义的。 If you want to convert a Java null to a JavaScript null, you'll need to consult your conversion library. 如果要将Java null转换为JavaScript null,则需要查阅转换库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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