How do I POST a Pojo with Jersey Client without manually convert to JSON?(如何在不手动转换为 JSON 的情况下使用 Jersey 客户端发布 Pojo?)
问题描述
我有一个可用的 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
}
查询对象看起来像这样,当发布该查询对象的 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 对象然后作为字符串发布的情况下完成.
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.
推荐答案
如果您的 Web 服务生成 JSON,您必须在客户端使用 accept() 方法处理它:
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);
试试这个并给出你的结果.
Try this and give your results.
这篇关于如何在不手动转换为 JSON 的情况下使用 Jersey 客户端发布 Pojo?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在不手动转换为 JSON 的情况下使用 Jersey 客户端发布 Pojo?
基础教程推荐
- Maven:无效的目标版本:10 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- JPA惰性列表上的流 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
