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.
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.
For serialization, and or deserialization, you can create JSON facade classes for yout object, which will help you out, to serialize and deserialize objects.
And i will suggest not to use colletion in such objects which you pass over some servelet, or network, it makes the transportation object very heavy, instead use normal arrays. That will ease your problem.
Have you tried
Gadget[] result = r.get(Gadget[].class);
The above works for me.
精彩评论