简体   繁体   中英

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

I'm working on a project which uses Jersey to convert objects to JSON. I'd like to be able to write out nested lists, like so:

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

The object I'd like to convert first represented data as a <LinkedList<LinkedList<String>>>, and I figured Jersey would just do the right thing. The above was output as a list of nulls:

{"data":[null, null]}

After reading that nested objects need to be wrapped, I tried the following:

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

That code outputs what's below, which is closer to what I want:

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

I want the first data to be a list of lists, not a list of one-element dictionaries. How do I achieve this?

Here's my 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;
    }
}

Have you tried jersey-json ??

Add jersey-json to your classpath (or your maven dependencies)

Then use this :

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

}

You only need something like this in your ressources (supposing DetailProduit is your object you want to serialize and that DetailProduit.java is jaxb tagged and in package.of.your.model)

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

Check out the "Improving the Application" section of this page:

http://blogs.oracle.com/enterprisetechtips/entry/configuring_json_for_restful_web

I know the qustion is rather old but I stumbled on a similar problem but I wanted to render a List of Arrays ie.´List´ due to a result from a db which I got from jpa and a nativ query without using Entities.

This is how I solved it:

First Created a 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);
    }
}

And then I created a class extending 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);
        }
    }
}

Then I using it in a as this:

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

The search method is returning a Listwrapper with a list of Object[]

Hope this helps someone :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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