Java 如何在不手动转换为JSON的情况下发布带有Jersey客户端的Pojo?
我有一个工作的json服务,如下所示:Java 如何在不手动转换为JSON的情况下发布带有Jersey客户端的Pojo?,java,json,client,jersey,jackson,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 } 查询对象如下所示,
@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;
}
我用的是泽西1.12
任何指向正确方向的帮助或指针都将不胜感激。如果您的web服务生成JSON,您必须使用
accept()
方法在客户端处理:
ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(searchQuery, MediaType.APPLICATION_JSON);
ListWrapper listWrapper = response.getEntity(ListWrapper.class);
尝试此方法并给出结果。WebResource.entity(…)方法不会更改您的WebResource实例。。。它创建并返回保存更改的生成器对象。对.post的调用通常从生成器对象执行,而不是从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;
}
下面是使用链接的相同示例。它仍在使用生成器,但不太明显
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-WebResource=client.resource(url);ClientResponse response=webResource.type(MediaType.APPLICATION\u JSON\u type).accept(MediaType.APPLICATION\u JSON).post(ClientResponse.class,searchQuery);ListWrapper=response.getEntity(ListWrapper.class)代码>现在我得到了一个JsonMappingException,但我认为这是json结果中的一个错误。我找不到WebResource
类。请提供进口代码!如果您使用的是1.x分支(OP指定的版本1.12),您可以在此处找到有关WebResource的详细信息: