[英]Cannot get JSON data from Jersey GET response
I was developing a restful web client and trying to get the JSON payload from the response of a GET method. 我正在开发一个宁静的Web客户端,并尝试从GET方法的响应中获取JSON有效负载。 I am using Jersey.
我正在使用泽西岛。 But I just cannot read the JSON data using response.getEntity() method.
但是我只是无法使用response.getEntity()方法读取JSON数据。 I tried many methods including response.bufferEntity(), but the output always kept empty.
我尝试了许多方法,包括response.bufferEntity(),但输出始终保持为空。 Below is my code and output, and in addition I can see the JSON data right in the response packet captured in wireshark.
以下是我的代码和输出,此外,我还可以在Wireshark中捕获的响应数据包中看到JSON数据。 I would really appreciate everyone trying to help figure out why or provide solution.
我非常感谢每个尝试帮助找出原因或提供解决方案的人。 Thank you!
谢谢!
Code: 码:
public JSONObject Get(String requestPath){
ClientResponse response = webResource.path(requestPath)
.header("Content-Type", contTypeHeader )
.header("Accept",acceptHeader)
.header("Authorization", authZ )
.get(ClientResponse.class);
response.bufferEntity();
if (!(response.getStatus() == 201 || response.getStatus() == 200)) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
System.out.println(response.getEntity(JSONObject.class));
return null;
}
and the output is always like this: {} 输出总是像这样:{}
You can't use JSONObject
unless you have a MessageBodyReader
for it. 除非您有
MessageBodyReader
,否则您不能使用JSONObject
。 See more at JAX-RS Entity Providers . 在JAX-RS实体提供者中查看更多内容。 The provider you are currently using (probably Jackson) only supports JavaBean POJOs or collections of them.
您当前正在使用的提供程序(可能是Jackson)仅支持JavaBean POJO或它们的集合。 For example if you have this JSON
例如,如果您有此JSON
{ "property1" : "value1", "property2": "value2" }
Then you would need to have a POJO like 然后,您需要像这样的POJO
public class Bean {
private String property1;
private String property2;
// getters and setters
}
Then you can do getEntity(Bean.class)
. 然后,您可以执行
getEntity(Bean.class)
。 The reason you are getting an empty object, is that the deserialization works off the setters. 之所以得到一个空对象,是因为反序列化可以解决设置程序的问题。 It looks for properties on the JSON, that matches a setters, and uses it the set the property.
它在JSON上查找与设置器匹配的属性,并使用它来设置属性。 The JSON object has no setters for your JSON properties.
JSON对象对你的JSON属性没有setter方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.