簡體   English   中英

如何使用Jersey將嵌套列表編組為JSON? 我得到一個空數組或一個包含數組的單元素字典數組

[英]How do I marshal nested lists as JSON using Jersey? I get an array of nulls or an array of one-element dictionaries containing an array

我正在開發一個使用Jersey將對象轉換為JSON的項目。 我希望能夠寫出嵌套列表,如下所示:

{"data":[["one", "two", "three"], ["a", "b", "c"]]}

我想要轉換的對象首先將數據表示為<LinkedList <LinkedList <String >>>,我認為Jersey會做正確的事情。 以上輸出為空值列表:

{"data":[null, null]}

在閱讀了需要包裝的嵌套對象之后,我嘗試了以下方法:

@XmlRootElement(name = "foo")
@XmlType(propOrder = {"data"})
public class Foo
{
    private Collection<FooData> data = new LinkedList<FooData>();

    @XmlElement(name = "data")
    public Collection<FooData> getData()
    {
        return data;
    }

    public void addData(Collection data)
    {
        FooData d = new FooData();
        for(Object o: data)
        {
            d.getData().add(o == null ? (String)o : o.toString());
        }
        this.data.add(d);
    }

    @XmlRootElement(name = "FooData")
    public static class FooData
    {
        private Collection<String> data = new LinkedList<String>();

        @XmlElement
        public Collection<String> getData()
        {
            return data;
        }
    }
}

該代碼輸出下面的內容,這更接近我想要的內容:

{"data":[{"data":["one", "two", "three"]},{"data":["a", "b", "c"]}]}

我希望第一個數據是列表列表,而不是單元素字典列表。 我該如何實現這一目標?

這是我的JAXBContentResolver:

@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext>
{
    private JAXBContext context;
    private Set<Class<?>> types;

    // Only parent classes are required here. Nested classes are implicit.
    protected Class<?>[] classTypes = new Class[] {Foo.class};

    protected Set<String> jsonArray = new HashSet<String>(1) {
        {
            add("data");
        }
    };

    public JAXBContextResolver() throws Exception
    {        
        Map<String, Object> props = new HashMap<String, Object>();
        props.put(JSONJAXBContext.JSON_NOTATION, JSONJAXBContext.JSONNotation.MAPPED);
        props.put(JSONJAXBContext.JSON_ROOT_UNWRAPPING, Boolean.TRUE);
        props.put(JSONJAXBContext.JSON_ARRAYS, jsonArray);
        this.types = new HashSet<Class<?>>(Arrays.asList(classTypes));
        this.context = new JSONJAXBContext(classTyes, props);
    }

    public JAXBContext getContext(Class<?> objectType)
    {
        return (types.contains(objectType)) ? context : null;
    }
}

你試過jersey-json嗎?

將jersey-json添加到您的類路徑(或您的maven依賴項)

然后用這個:

@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {

    private final JAXBContext context;

    public JAXBContextResolver() throws Exception {
        this.context = new JSONJAXBContext(JSONConfiguration.natural().build(), "package.of.your.model");
    }

    public JAXBContext getContext(Class<?> objectType) {
        return context;
    }

}

你只需要在你的資源中需要這樣的東西(假設DetailProduit是你要序列化的對象,而且DetailProduit.java是jaxb標記的,並且在package.of.your.model中)

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{code}")
public DetailProduit getDetailProduit(@PathParam("code") String code) {
        .... Your Code ........
    }

我知道qustion相當陳舊,但我偶然發現了一個類似的問題,但我想渲染一個數組列表ie.'List',因為我從jpa得到的數據庫結果和不使用實體的nativ查詢。

這就是我解決它的方式:

首先創建一個ListWrapper.java:

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class ListWrapper extends ArrayList {

    @SuppressWarnings("unchecked")
    public ListWrapper() {
        super();
    }

    public ListWrapper(List list) {
        super(list);
    }
}

然后我創建了一個擴展AbstractMessageReaderWriterProvider的類

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;

import com.sun.jersey.core.provider.AbstractMessageReaderWriterProvider;

@Provider
@Produces("*/*")
@Consumes("*/*")
public class ListObjectArrayMessagereaderWriterProvider extends    AbstractMessageReaderWriterProvider<ListWrapper> {

    public boolean supports(Class type) {
        return type == ListWrapper.class;
    }

    @Override
    public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return type == ListWrapper.class;
    }

    @Override
    public ListWrapper readFrom(Class<ListWrapper> type, Type genericType, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
        throw new IllegalArgumentException("Not implemented yet.");
    }

    @Override
    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return type == ListWrapper.class;
    }

    @SuppressWarnings("unchecked")
    @Override
    public void writeTo(ListWrapper t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {

        final Iterator<Object[]> iterator = t.iterator();

        OutputStreamWriter writer = new OutputStreamWriter(entityStream, getCharset(mediaType));
        final JSONArray jsonArrayOuter = new JSONArray();
        while (iterator.hasNext()) {
            final Object[] objs = iterator.next();
            JSONArray jsonArrayInner = new JSONArray(Arrays.asList(objs));
            jsonArrayOuter.put(jsonArrayInner);
        }
        try {
            jsonArrayOuter.write(writer);
            writer.write("\n");
            writer.flush();
        } catch (JSONException je) {
            throw new WebApplicationException(new Exception(ImplMessages.ERROR_WRITING_JSON_ARRAY(), je), 500);
        }
    }
}

然后我在這里使用它:

    @GET
    @Path("/{id}/search")
    @Produces(JSON)
    public ListWrapper search(@PathParam("id") Integer projectId ) {
        return DatabaseManager.search(projectId);
    }

搜索方法返回一個Listwrapper,其中包含Object []列表

希望這有助於某人:-)

暫無
暫無

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

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