2012-04-26 44 views
8

我有一个工作的JSON服务,看起来像这样:如何在没有手动转换为JSON的情况下使用Jersey客户端发布Pojo?

@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对象,然后以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; 
} 

我使用的是泽西岛1.12。

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

回答

3

如果您的网络服务产生JSON你必须处理在客户端通过使用accept()方法:

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

试试这个,给你的结果。

+1

谢谢! 你让我在正确的轨道与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结果中的错误。 – Perty 2012-04-26 16:14:28

+0

对不起我的标记: -/ – Perty 2012-04-26 16:25:11

5

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

谢谢,这也像魅力工作! – Perty 2012-04-26 16:31:30

+0

我找不到'WebResource'类。请给出进口代码! – 2015-04-26 04:56:36

+0

如果您使用1.x分支(OP指定的版本1.12),您可以在这里找到有关WebResource的详细信息:https://jersey.java.net/nonav/apidocs/1.9/jersey/com/sun/jersey /api/client/WebResource.html – phatfingers 2015-04-27 04:13:01

相关问题