我希望你能帮助我解决让我发疯的事情
我在这里有这个简单的Json:
{"2":{"picture":"0","id":52,"bought_date":"2014-08-01","mileage":0,"bike_id":21861,"hours":0,"name":"YZ450F","pictures":"","year":2013,"user_id":34,"cost":8000},"1":{"picture":"140","id":51,"bought_date":"2014-07-28","mileage":0,"bike_id":21130,"hours":0,"name":"Yamaha WR450F 2013","pictures":"","year":2013,"user_id":34,"cost":0},"0":{"picture":"0","id":53,"bought_date":"2014-08-01","mileage":0,"bike_id":18310,"hours":0,"name":"MX 300","pictures":"","year":2011,"user_id":34,"cost":0}}
我将此JSONObject发送到Display_Bikes(),它应该迭代JSONObject的每个元素,然后选择每个id值以触发另一个方法
在伪代码中它看起来像这样
foreach Json as bike{
get bike.id then
call anothermethod(bike.id)
}
在现实中,我不知道我做错了什么,这是我第四天使用Java,所以这是可以理解的,但我真的很沮丧
这是我正在研究的幼稚方法,非常感谢任何帮助:
public static void Display_Bikes(JSONObject Bikes){
Log.v("Bikes", Bikes.toString());
Iterator<String> iter = Bikes.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object Bike = Bikes.get(key).toString();
Log.v("Bike", Bike.toString());
//Now, how to get Bike.id?
}
catch(JSONException e){
//error
}
}
}
答案 0 :(得分:2)
您可以使用getJSONObject(String key)
获取内部对象:
while (iter.hasNext()) {
String key = iter.next();
try {
JSONObject bike = Bikes.getJSONObject(key);
Log.v("Bike", bike.toString());
int id = bike.getInt("id");
} catch(JSONException e) {}
}