简体   繁体   English

使用 json-array 的球衣客户端将无法工作

[英]jersey client that consumes json-array won't work

I know there's some answers out there but none of them really solved my problem.我知道那里有一些答案,但没有一个能真正解决我的问题。 I'm really glad for all the input I can get.我真的很高兴我能得到所有的投入。 Thx in advance.提前谢谢。

The Service I try to consume is a jersey rs 1.8 which I try to 'GET'.我尝试使用的服务是我尝试“获取”的球衣 rs 1.8。 The Service is annotated with '@Produces(MediaType.APPLICATION_JSON)' and returns the following:该服务使用“@Produces(MediaType.APPLICATION_JSON)”进行注释并返回以下内容:

[{"projRnd":"1","firstname":"Jadeveon","lastname":"Clowney"},{"projRnd":"1","firstname":"Greg","lastname":"Robinson"}, ..]

Now my Service Consumer does the following:现在我的服务消费者执行以下操作:

import org.json.simple.JSONArray;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
...
WebResource webResource = client.resource(URL to my ws);
JSONArray jsonObjects = webResource.accept(MediaType.APPLICATION_JSON_TYPE).get(JSONArray.class);

Tomcat says: Tomcat 说:

HTTP Status 500
javax.servlet.ServletException: com.sun.jersey.api.client.ClientHandlerException: A message body reader for Java class org.json.simple.JSONArray, and Java type class org.json.simple.JSONArray, and MIME media type application/json was not found
...

To clarify ... the client runs on a vaadin application in the frontend ... the HTTP 500 is not from the backend.为了澄清......客户端在前端的vaadin应用程序上运行...... HTTP 500不是来自后端。

My pom.xml sure has the right dependency:我的 pom.xml 肯定有正确的依赖:

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-server</artifactId>
    <version>1.8</version>
</dependency>

Like I said ... all the Input is much appreciated.就像我说的......所有的输入都非常感谢。

.. so I solved the Problem... first of all you shouldn't do something like: ..所以我解决了这个问题......首先你不应该做这样的事情:

JSONArray jsonObjects = webResource.accept(MediaType.APPLICATION_JSON_TYPE).get(JSONArray.class);

I changed the service so the response looks like:我更改了服务,因此响应如下所示:

{"prospectList":[{"projRnd":"1","firstname":"Jadeveon","lastname":"Clowney"},{"projRnd":"1","firstname":"Greg","lastname":"Robinson"}, ..]}

The way to get the JSONArray from this is pretty straight forward with a JSONParser which I didn't even try to use in the first place (FAIL!).使用 JSONParser 从中获取 JSONArray 的方法非常简单,我什至没有尝试使用它(失败!)。

ClientResponse response = webResource.accept("application/json")
        .type("application/json").get(ClientResponse.class);
String s = response.getEntity(String.class);
JSONParser parser = new JSONParser();
Object obj = parser.parse(s);
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonArray = (JSONArray) jsonObject.get("prospectList");

the returning jsonArray is iterable and the attributes of each element can now be accessed:返回的 jsonArray 是可迭代的,现在可以访问每个元素的属性:

(String) jsonObj.get("firstname");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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