使用自定义对象接收Rest API的json响应

时间:2015-03-08 21:56:49

标签: java jersey jersey-client

我已经使用Jersey设置了一个休息API服务,它产生了一个json响应。这是服务器代码:

@Path("/addNumservice")
public class AddNumService {
    @GET
    @Produces("application/json")
    public Response addNum() throws JSONException {
        JSONObject jsonObject = new JSONObject();
        int x = 5, y = 4;
        int z = x + y; 
        jsonObject.put("Sum Value", z); 

        String result = "@Produces(\"application/json\") Output: \n\nNumber adding Output: \n\n" + jsonObject;
        return Response.status(200).entity(result).build();
    }
}

当我运行服务器时,我看到了预期的o / p:

@Produces("application/json") Output: 
Number adding Output: 
{"Sum Value":9}

现在我想设置一个客户端类来接收我定义的自定义对象AddNumResponseObject中的json响应,但是当我这样做时:

AddNumResponseObject object
      = webResource2.accept("application/json").get(AddNumResponseObject.class);
  

我收到此错误:Java类com.crunchify.client.AddNumResponseObject和Java类型类com.crunchify.client.AddNumResponseObject的消息正文阅读器,以及未找到MIME媒体类型application / json

有人可以帮帮我吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

您应该向项目中添加一个支持JSON到POJO的提供程序(反之亦然)。现在我在这里假设您正在使用Jersey 1(由名称webResource2推断)。在这种情况下,您应该添加此依赖项

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-json</artifactId>
    <version>${jersey-version}</version>
</dependency>

然后将其注册到客户端

ClientConfig config = new DefaultClientConfig();
//config.getClasses().add(JacksonJsonProvider.class);
config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, 
                                               Boolean.TRUE);
Client c = Client.create(config);

对于服务器配置(如果需要)或Jersey 2支持,请参阅this post。另请参阅here

相关问题