如何在不手动转换为JSON的情况下使用Jersey客户端发布Pojo? [英] How do I POST a Pojo with Jersey Client without manually convert to JSON?
问题描述
我有一个工作的json服务,如下所示:
I have a working json service which looks like this:
@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表示时,它很好用。
The query object looks like this and when posting a json representation of that Query object it works out nice.
@XmlRootElement
public class Query {
Integer id;
String query;
... // Getters and Setters etc..
}
现在我想从客户端填充该对象,并使用Jersey客户端将该Query对象发布到服务并获取JSONObject作为结果。我的理解是,它可以在不首先将其转换为json对象然后作为String发布的情况下完成。
Now I want to fill that object from a client and use Jersey client to post that Query object to the service and get an JSONObject as a result. My understanding is that it could be done without converting it to a json object first and then posted as a String.
我尝试了类似的东西,但我想我想念一些东西。
I have tried something like this but I think I miss something.
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。
I'm using Jersey 1.12.
非常感谢正确方向的任何帮助或指针。
Any help or pointer in the right direction would be much appreciated.
推荐答案
如果您的网络服务产生您必须使用 accept()
方法在客户端处理JSON:
If your web-service produces a JSON you must handle that in your client by using an accept()
method:
ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(searchQuery, MediaType.APPLICATION_JSON);
ListWrapper listWrapper = response.getEntity(ListWrapper.class);
试试这个并给出结果。
这篇关于如何在不手动转换为JSON的情况下使用Jersey客户端发布Pojo?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!