Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize JSON response from Jersey REST service to collection of java objects

Tags:

java

json

jersey

I write client that makes GET request to REST service using Jersey Client API. Response is a collection of objects, and I need to deserialize it. Here is my code:

    ClientConfig clientConfig = new DefaultClientConfig();
    clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING,
            Boolean.TRUE);
    Client client = Client.create(clientConfig);
    WebResource r = client
            .resource("http://localhost:8080/rest/gadgets");

and class that represents "gadget" model (annotated with @XmlRootElement for JAXB processing):

    @XmlRootElement
public class Gadget {

    private String url;
    private String title;
    private String name;

    public Gadget() {
}


public String getUrl() {
    return url;
}

public void setUrl(String url) {
    this.url = url;
}


public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getName() {
    return name;
}

    public void setName(String name) {
        this.name = name;
    }
}

If response would just Gadget copy, not a collection, the could looked as

Gadget result = r.get(Gadget.class);

But JSON in response contains a list of gadgets, and I need to read it to java collection. Something like

List<Gadget> result = r.get(List<Gadget>.class);

doesn't compile. Can somebody help me here? I don't want to use any additional libs, I believe this can be done using jersey-json.jar and JAXB, but don't know how.

like image 217
Mikhail Avatar asked Jun 14 '11 06:06

Mikhail


1 Answers

I think you want to use an anonymous subclass of GenericType:

r.get(new GenericType<List<Gadget>>() {});

List<Gadget>.class won't work because of type erasure.

like image 118
tbi Avatar answered Oct 17 '22 22:10

tbi