gpt4 book ai didi

java - 使用 json-array 的 Jersey 客户端将无法工作

转载 作者:行者123 更新时间:2023-11-29 00:00:22 25 4
gpt4 key购买 nike

我知道那里有一些答案,但没有一个能真正解决我的问题。我真的很高兴能得到所有的意见。提前致谢。

我尝试使用的服务是一件 Jersey rs 1.8,我尝试“获取”它。该服务用“@Produces(MediaType.APPLICATION_JSON)”注释并返回以下内容:

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

现在我的服务消费者执行以下操作:

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 说:

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
...

为了澄清......客户端在前端的 vaadin 应用程序上运行......HTTP 500 不是来自后端。

我的 pom.xml 确实具有正确的依赖关系:

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

就像我说的......非常感谢所有的输入。

最佳答案

.. 所以我解决了问题......首先你不应该做这样的事情:

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

我更改了服务,因此响应如下所示:

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

使用 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");

返回的 jsonArray 是可迭代的,现在可以访问每个元素的属性:

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

关于java - 使用 json-array 的 Jersey 客户端将无法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22833508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com