如何在不手动转换为 JSON 的情况下使用 Jersey 客户端发布 Pojo?

Posted

技术标签:

【中文标题】如何在不手动转换为 JSON 的情况下使用 Jersey 客户端发布 Pojo?【英文标题】:How do I POST a Pojo with Jersey Client without manually convert to JSON? 【发布时间】:2012-05-07 07:22:51 【问题描述】:

我有一个可用的 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 客户端将该 Query 对象发布到服务并获得 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。

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

【问题讨论】:

【参考方案1】:

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;

【讨论】:

我找不到WebResource 类。请给出导入码! 如果您使用的是 1.x 分支(OP 指定版本 1.12),您可以在此处找到有关 WebResource 的详细信息:jersey.java.net/nonav/apidocs/1.9/jersey/com/sun/jersey/api/…【参考方案2】:

如果您的网络服务生成 JSON,您必须在客户端中使用 accept() 方法处理它:

ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(searchQuery, MediaType.APPLICATION_JSON);
ListWrapper listWrapper = response.getEntity(ListWrapper.class);

试试这个并给出你的结果。

【讨论】:

谢谢!您通过 ClientResponse 让我走上了正轨。我还必须做一些额外的事情:WebResource webResource = client.resource(url); ClientResponse response = webResource.type(MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, searchQuery); ListWrapper listWrapper = response.getEntity(ListWrapper.class); 现在我得到了 JsonMappingException ,但我认为这是 json 结果中的错误。

以上是关于如何在不手动转换为 JSON 的情况下使用 Jersey 客户端发布 Pojo?的主要内容,如果未能解决你的问题,请参考以下文章

Postgresql:如何在不使用中间 hstore 的情况下将键值表转换为 json

如何在不将 LocalDateTime 字段转换为扩展的 json 对象的情况下将 java 对象转换为简单的 json 字符串?

如何在不转换为json的情况下将C#数组用于javascript数组?

Jackson 如何在不强制转换的情况下将 JsonNode 转换为 ArrayNode?

如何在不使用转储的情况下在 python 中编写 json 文件

如何在不使用向导的情况下手动为编辑控件等控件添加控件变量并使用它?