gpt4 book ai didi

java - 如何在不手动转换为 JSON 的情况下使用 Jersey Client 发布 Pojo?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:19:56 24 4
gpt4 key购买 nike

我有一个工作中的 json 服务,如下所示:

@POST
@Path("/{id}/query")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(JSON)
public ListWrapper query(@Context SecurityContext sc, @PathParam("id") Integer projectId, Query searchQuery) {
...
return result
}

查询对象看起来像这样,当发布该查询对象的 json 表示时,效果很好。

@XmlRootElement
public class Query {
Integer id;
String query;
... // Getters and Setters etc..
}

现在我想从客户端填充该对象并使用 Jersey 客户端将该查询对象发布到服务并获得一个 JSONObject 作为结果。我的理解是,无需先将其转换为 json 对象,然后将其作为字符串发布即可完成。

我试过类似的东西,但我想我错过了什么。

public static JSONObject query(Query searchQuery){
String url = baseUrl + "project/"+searchQuery.getProjectId() +"/query";
WebResource webResource = client.resource(url);
webResource.entity(searchQuery, MediaType.APPLICATION_JSON_TYPE);
JSONObject response = webResource.post(JSONObject.class);
return response;
}

我正在使用 Jersey 1.12。

任何正确方向的帮助或指示将不胜感激。

最佳答案

WebResource.entity(...) 方法不会改变您的 webResource 实例...它创建并返回一个包含更改的 Builder 对象。您对 .post 的调用通常是从 Builder 对象而不是 WebResource 对象执行的。当所有请求链接在一起时,这种转换很容易被掩盖。

public void sendExample(Example example) {
WebResource webResource = this.client.resource(this.url);
Builder builder = webResource.type(MediaType.APPLICATION_JSON);
builder.accept(MediaType.APPLICATION_JSON);
builder.post(Example.class, example);
return;
}

这是使用链接的相同示例。它仍在使用 Builder,但不太明显。

public void sendExample(Example example) {
WebResource webResource = this.client.resource(this.url);
webResource.type(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.post(Example.class, example);
return;
}

关于java - 如何在不手动转换为 JSON 的情况下使用 Jersey Client 发布 Pojo?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10335483/

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