【问题标题】:Cannot get JSON data from Jersey GET response无法从 Jersey GET 响应中获取 JSON 数据
【发布时间】:2016-01-06 23:16:08
【问题描述】:

我正在开发一个 RESTful Web 客户端并尝试从 GET 方法的响应中获取 JSON 有效负载。我正在使用泽西岛。但我无法使用 response.getEntity() 方法读取 JSON 数据。我尝试了许多方法,包括 response.bufferEntity(),但输出始终为空。下面是我的代码和输出,此外,我可以在 wireshark 中捕获的响应数据包中看到 JSON 数据。我非常感谢每个试图帮助找出原因或提供解决方案的人。谢谢!

代码:

    public JSONObject Get(String requestPath){

    ClientResponse response = webResource.path(requestPath)
            .header("Content-Type", contTypeHeader )
            .header("Accept",acceptHeader)
            .header("Authorization", authZ )
            .get(ClientResponse.class);

    response.bufferEntity();
    if (!(response.getStatus() == 201 || response.getStatus() == 200)) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }

    System.out.println(response.getEntity(JSONObject.class));
    return null;

}

输出总是这样:{}

【问题讨论】:

    标签: java json http jersey response


    【解决方案1】:

    你不能使用JSONObject,除非你有一个MessageBodyReader。在JAX-RS Entity Providers 上查看更多信息。您当前使用的提供者(可能是 Jackson)仅支持 JavaBean POJO 或它们的集合。例如,如果你有这个 JSON

    { "property1" : "value1", "property2": "value2" }
    

    那么你需要一个类似 POJO 的东西

    public class Bean {
        private String property1;
        private String property2;
        // getters and setters
    }
    

    那你就可以getEntity(Bean.class)了。你得到一个空对象的原因是反序列化对设置器起作用。它在 JSON 上查找与 setter 匹配的属性,并使用它来设置属性。 JSON 对象没有您的 JSON 属性的设置器。

    【讨论】:

    • 感谢您的回答。如果 JSON 稍微复杂一点怎么办: { "vtn": [ { "description": "VTN Hao", "name": "Tenant_Hao", "hardTimeout": "0", "idleTimeout": "300 " }, { "description": "VTN Jue", "name": "Tenant_Jue", "hardTimeout": "0", "idleTimeout": "300" } ] } 并且条目数不确定。如何定义 POJO?
    • 您需要完成一些 Jackson 教程。开始herehere
    • 基本上使用您提供的内容,只需使用带有vtn 类型为List<SomeObject> 的属性的pojo。 SomeObject 应该具有descriptionname 等属性
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多