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

标签 java json client jersey jackson

我有一个工作中的 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/

相关文章:

java - Java 线程中的同步

javascript - 本地存储功能

javascript - 在 jQuery $.each 循环中暂停 JSON 项的执行

C++ Qt - QTcpSocket 发出 readyRead() 但 canReadLine() 始终为 false

windows - 没有管理员权限的用户的独立 Mercurial(或其他 SCM)客户端?

javafx场景中的javafx线程异常

java - 每次切换 Activity 时 dubbel json 输出

java - 从另一个线程取消 MySQL 查询执行

javascript - 强制 JSON.stringify 转义正斜杠(即 `\/` )

java - 如何修复“File.exists()”错误的 boolean 返回值?