0

我正在编写一个应用程序来使用他们的 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 相关的灯光对象。

任何人都知道如何用改造来解析这个?

4

2 回答 2

1

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

在 Gson 中,您还可以创建自定义反序列化器,有很多资源可用于学习如何创建反序列化器。

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

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

迭代这个 nodeSet 和

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

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

于 2015-06-29T15:23:43.360 回答
0

基于这个 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;
    ...
}
于 2017-03-23T07:58:59.737 回答