我有下面的json字符串,
"objects": [{
"d430f6c0-a293-4fb9-86fe-a163618cf180": {
"id": "d430f6c0-a293-4fb9-86fe-a163618cf180",
"in_use": 0,
"alterable": 1,
"comment": ""
},
"123-a293-4fb9-86fe-a163618cf180": {
"id": "123-a293-4fb9-86fe-a163618cf180",
"in_use": 2,
"alterable": 3,
"comment": "dfgfg"
}
}]
并且无法找到解析它的方法,数组中的所有对象前面都有 id,如上所示。提前感谢您的帮助。
首先,您的 json 数组格式错误,您可以检查一下 jsonviewer您的 JSON 数据将如下所示:
{"objects": [{
"d430f6c0-a293-4fb9-86fe-a163618cf180": {
"id": "d430f6c0-a293-4fb9-86fe-a163618cf180",
"in_use": 0,
"alterable": 1,
"comment": ""
},
"123-a293-4fb9-86fe-a163618cf180": {
"id": "123-a293-4fb9-86fe-a163618cf180",
"in_use": 2,
"alterable": 3,
"comment": "dfgfg"
}
}]}
现在要解析此数据,您可以使用此方法:
public void parseData(String jsonObjectData) {
try {
JSONObject jsonObject = new JSONObject(jsonObjectData);
JSONArray jsonArray = jsonObject.getJSONArray("objects");
for (int i = 0 ; i <jsonArray.length(); i ++)
{
String id = jsonArray.getJSONObject(i).getJSONObject("d430f6c0-a293-4fb9-86fe-a163618cf180").getString("id");
Log.d("id", id);
}
} catch (Exception e) {
}
}
你必须像这样获取 JSON 对象String id = jsonArray.getJSONObject(i).getJSONObject("d430f6c0-a293-4fb9-86fe-a163618cf180").getString("id");
它将提供单个对象数据,您无法获取所有数据,因为您的 JSON 格式不正确。