如何使用Retrofit来解析使用唯一id作为键的JSON响应?

时间:2015-06-29 14:11:27

标签: android json rest retrofit philips-hue

我正在编写一个应用程序来使用他们的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"
    }
}

} ```

请注意,它不是返回一个光对象数组,而是返回每个灯光对象的光标识。

任何人都知道如何使用Retrofit来解析它?

2 个答案:

答案 0 :(得分:1)

Retrofit使用GSON反序列化它接收的json,而json又使用一个类来理解你正在为它提供的json。

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

你可以在反序列化器中做的是获取json对象的键集并迭代它。您可以获得类似

的密钥集
Set<Map.Entry<String, JsonElement>> nodeSet = jsonObject.entrySet();

迭代此nodeSet和

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

currentValue将包含“state”,“type”等元素的JsonObject。

答案 1 :(得分:0)

基于此StackOverflow问题Retrofit parse JSON dynamic keys

的答案

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

ArrayTable.create(new ImmutableTable.Builder<Integer, Character, String>()
       .put(1, 'A', "foo")
       .put(1, 'B', "bar")
       .put(2, 'A', "baz")
       .build())