如何将来自 Jersey REST 服务的 JSON 响应反序列化为 Java 对象集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6339910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to deserialize JSON response from Jersey REST service to collection of java objects
提问by Mikhail
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:
我编写了使用 Jersey 客户端 API 向 REST 服务发出 GET 请求的客户端。响应是对象的集合,我需要反序列化它。这是我的代码:
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 注释以进行 JAXB 处理):
@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
但是响应中的 JSON 包含一个小工具列表,我需要将其读取到 java 集合。就像是
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.
不编译。有人可以在这里帮助我吗?我不想使用任何额外的库,我相信这可以使用 jersey-json.jar 和 JAXB 来完成,但不知道如何。
回答by tbi
I think you want to use an anonymous subclass of GenericType:
我认为您想使用GenericType的匿名子类:
r.get(new GenericType<List<Gadget>>() {});
List<Gadget>.class
won't work because of type erasure.
List<Gadget>.class
由于类型擦除而无法工作。
回答by M.J.
For serialization, and or deserialization, you can create JSON facade classes for yout object, which will help you out, to serialize and deserialize objects.
对于序列化和/或反序列化,您可以为您的对象创建 JSON 外观类,这将帮助您序列化和反序列化对象。
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.
我建议不要在通过一些小服务或网络的对象中使用集合,它会使传输对象非常重,而是使用普通数组。那会缓解你的问题。
回答by Bab
Have you tried
你有没有尝试过
Gadget[] result = r.get(Gadget[].class);
The above works for me.
以上对我有用。