我正在写一个应用程序来控制飞利浦色调智能灯使用他们的REST API和Square的Retrofit库。
问题是,当我调用/lights时,响应返回时使用每个光的id属性作为json响应中的键(而不是jsonapi响应中典型的光对象数组,这似乎是Retrofit所期望的)。
下面是我正在查看的请求/响应
GET /lights
返回
```javascript"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来解析这个?
发布于 2015-06-29 23:23:43
Retrofit使用GSON来反序列化它接收的json,而json又使用一个类来理解您提供给它的json。
在Gson中,你也可以创建一个自定义的deserializer,有很多资源可以学习如何创建一个。
您可以在反序列化程序中执行的操作是获取json对象的键集并对其进行迭代。您可以获得密钥集,如下所示
Set<Map.Entry<String, JsonElement>> nodeSet = jsonObject.entrySet();遍历此nodeSet和
for(Map.Entry<String, JsonElement> entryItem : nodeSet) {
JsonObject currentValue = entryItem.getValue().getAsJsonObject();
}currentValue将包含“状态”、“类型”等元素的JsonObject。
发布于 2017-03-23 15:59:00
根据此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;
...
}https://stackoverflow.com/questions/31117924
复制相似问题