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

我有一个工作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 } 

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

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

现在我想从客户端填充该对象,并使用Jersey客户端将该Query对象发布到服务并获取JSONObject作为结果。 我的理解是,它可以在不首先将其转换为json对象然后作为String发布的情况下完成。

我尝试过类似的东西,但我觉得我错过了一些东西。

 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。

任何帮助或指针在正确的方向将非常感激。

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

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

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

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; }