5

我有一个类,我想通过 Jersey RESTful API 公开。它看起来类似于:

@XmlRootElement
public class Data {
    public String firstName;
    public String lastName;
}

我的问题是这些字段可能为空,在这种情况下,JSON 输出中省略了该字段。我希望所有字段都存在,无论它们的价值如何。例如,如果 lastName 为 null,则 JSON 输出将为:

{
   "firstName" : "Oleksi"
}

而不是我想要的:

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

我有一个如下所示的 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;
    }
}

一段时间以来,我一直试图弄清楚如何获得所需的输出,但我没有运气。我愿意尝试其他的 ContextResolvers/Serializers,但我找不到一个可以工作的,所以代码示例会很好。

4

2 回答 2

11

对于EclipseLink JAXB (MOXy)的 JSON 绑定,正确的映射如下。您可以与您的提供商一起尝试,看看它是否也可以工作:

@XmlRootElement
public class Data {
    @XmlElement(nillable=true)
    public String firstName;

    @XmlElement(nillable=true)
    public String lastName;
}

了解更多信息


更新 2

EclipseLink 2.4 包含/MOXyJsonProvider的实现,您可以直接使用它来利用 MOXy 的 JSON 绑定MessageBodyReaderMessageBodyWriter

更新 1

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

}
于 2012-05-02T20:29:36.150 回答
-2

Java null 是 JavaScript 的未定义。如果要将 Java null 转换为 JavaScript null,则需要查阅转换库。

于 2012-05-02T20:24:15.000 回答