簡體   English   中英

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

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

我有一個類,我想通過Jersey RESTful API公開。 它看起來類似於:

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

我的問題是這些字段可能為null,在這種情況下,字段從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,但我找不到一個有效的代碼示例,所以代碼示例會很好。

對於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 ,它是MessageBodyReader / MessageBodyWriter一個實現,您可以直接使用它來利用MOXy的JSON綁定

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

}

Java null是JavaScript未定義的。 如果要將Java null轉換為JavaScript null,則需要查閱轉換庫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM