我的for (int i = 0; i <= response.length(); i++) {
JSONObject lightObject = response.getJSONObject(String.valueOf(i));
System.out.println("OBJECT " + lightObject);
// Use try/catch because of empty or unknown key
try {
description = lightObject.getString("type");
} catch (Exception e) {}
try {
bri = lightObjectState.getInt("bri");
} catch (Exception e) {}
try {
sat = lightObjectState.getInt("sat");
} catch (Exception e) {}
try {
hue = lightObjectState.getInt("hue");
} catch (Exception e) {}
Light light = new Light(String.valueOf(i),lightObject.getString("name"), description, on, bri, sat, hue);
mLightList.add(light);
mLightAdapter.notifyDataSetChanged();
}
包含其他对象:
no value of 0
飞利浦Hue Brigde JSON的响应包含所有连接的灯光。我使用Volley进行http连接。 我创建了一个Light类,我存储了像state,hue,bri等数据。我通过在Volley的onResponse中使用for循环来填充Light类:
key
for循环的问题在于,当Light id以大于零开始时,它将使我的Android应用程序崩溃,因为有JSONObject
。
我的问题是如何在不知道包含具有一个灯光的所有属性的对象的{
"4" : {
"state": [],
"hue": 224
}
"5" : {
"state": [],
"hue": 224
}
"6" : {
"state": [],
"hue": 224
}
}
名称的情况下获取响应的第一个对象,因此当{
"data": [
{
"target": "test-series-0",
"datapoints": [
[
22.504392773143504,
1.476693264195e+12
],
[
22.719552781746028,
1.476693301825e+12
]
]
}
]
}
如下所示时,应用程序将不会崩溃,但只显示4到6的光:
{
"data": [
{
"target": "test-series-0",
"datapoints": [
[
1.476693264195e+12
22.504392773143504,
],
[
1.476693301825e+12
22.719552781746028,
]
]
}
]
}
如果还有任何问题,请告诉我。 感谢。
答案 0 :(得分:2)
// use keys() iterator, you don't need to know what keys are there/missing
Iterator<String> iter = response.keys();
while (iter.hasNext()) {
String key = iter.next();
JSONObject lightObject = response.getJSONObject(key);
System.out.println("key: " + key + ", OBJECT " + lightObject);
// you can check if the object has a key before you access it
if (lightObject.has("bri")) {
bri = lightObject.getInt("bri");
}
if (lightObject.has("sat")) {
sat = lightObject.getInt("sat");
}
if (lightObject.has("hue")) {
hue = lightObject.getInt("hue");
}
if (lightObject.has("name")) {
name = lightObject.getString("name")
}
Light light = new Light(key, name, description, on, bri, sat, hue);
mLightList.add(light);
}
mLightAdapter.notifyDataSetChanged();
答案 1 :(得分:0)
尝试使用对象键:
Iterator<String> keys = jsonObject.keys();
if( keys.hasNext() ){
String key = (String)keys.next(); // First key in your json object
}
答案 2 :(得分:0)
假设您有一个名为Bulb的课程
public class Bulb {
int[] state;
int hue;
}
然后你可以使用像GSON
这样的JSON序列化器然后你可以将你的回复映射到地图(如HashMap),就像这样
Type typeOfHashMap = new TypeToken<Map<String, Bulb>>() { }.getType();
Map<String,Bulb> bulbMap = gson.fromJson(json, typeOfHashMap);
然后你可以用这样的键遍历地图
Iterator bulbIterator = bulbMap.entrySet().iterator();
while (bulbIterator.hasNext()) {
Map.Entry pair = (Map.Entry)bulbIterator.next();
String pKey = (String) pair.getKey();
Bulb bulb = (Bulb) pair.getValue();
// Do something here with the bulb
}