【问题标题】:How to use Retrofit to parse JSON response that uses the unique id as key?如何使用 Retrofit 解析使用唯一 id 作为键的 JSON 响应?
【发布时间】:2015-06-29 14:11:26
【问题描述】:

我正在编写一个应用程序来使用他们的 REST API 和 Square 的 Retrofit 库来控制飞利浦 Hue 智能灯。

问题是,当我调用 /lights 时,响应返回时使用每个灯光的 id 属性作为 json 响应中的键(而不是 jsonapi 响应中典型的灯光对象数组,这似乎是 Retrofit 所期望的)。

这是我正在查看的请求/响应

GET /lights

返回

``` {

"1": {
    "state": {
        "on": true,
        "bri": 144,
        "hue": 13088,
        "sat": 212,
        "xy": [0.5128,0.4147],
        "ct": 467,
        "alert": "none",
        "effect": "none",
        "colormode": "xy",
        "reachable": true
    },
    "type": "Extended color light",
    "name": "Hue Lamp 1",
    "modelid": "LCT001",
    "swversion": "66009461",
    "pointsymbol": {
        "1": "none",
        "2": "none",
        "3": "none",
        "4": "none",
        "5": "none",
        "6": "none",
        "7": "none",
        "8": "none"
    }
},
"2": {
    "state": {
        "on": false,
        "bri": 0,
        "hue": 0,
        "sat": 0,
        "xy": [0,0],
        "ct": 0,
        "alert": "none",
        "effect": "none",
        "colormode": "hs",
        "reachable": true
    },
    "type": "Extended color light",
    "name": "Hue Lamp 2",
    "modelid": "LCT001",
    "swversion": "66009461",
    "pointsymbol": {
        "1": "none",
        "2": "none",
        "3": "none",
        "4": "none",
        "5": "none",
        "6": "none",
        "7": "none",
        "8": "none"
    }
}

} ```

请注意,它不是返回一个灯光对象数组,而是返回每个灯光对象与其灯光 ID 相关联。

有人知道如何用 Retrofit 解析这个吗?

【问题讨论】:

  • 你使用 GSON 或类似的东西吗? AFAIR GSON 无法解析带注释字段的正则表达式,因此看起来最好的方法是使用 Jackson 库进行解析并手动将其转换为数组。

标签: android json rest retrofit philips-hue


【解决方案1】:

Retrofit 使用 GSON 反序列化它接收到的 json,而后者又使用一个类来理解您提供给它的 json。

在 Gson 中,您还可以创建自定义 deserializer,有很多资源可供学习如何创建。

您可以在反序列化器中做的是获取 json 对象的键集并对其进行迭代。你可以得到像

这样的keyset
Set<Map.Entry<String, JsonElement>> nodeSet = jsonObject.entrySet();

迭代这个nodeSet和

for(Map.Entry<String, JsonElement> entryItem : nodeSet) {
        JsonObject currentValue = entryItem.getValue().getAsJsonObject();
}

currentValue 将是包含“状态”、“类型”等元素的 JsonObject。

【讨论】:

    【解决方案2】:

    基于这个 StackOverflow 问题Retrofit parse JSON dynamic keys的答案

    使用包含单个地图字段的类

    class Lights { 
        // key is id of the light
        // value is the Light object which contains all the attributes
        Map<String, Light> allLights;
    }
    
    class Light {
        // all the attributes
        State state;
        String type;
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-14
      • 2015-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-19
      相关资源
      最近更新 更多