我正在构建一个需要下载并与在线数据库同步的Android应用程序,我将我的查询从应用程序发送到php页面,该页面以JSON格式从数据库返回相关行.
有人可以告诉我迭代JSON数组的最佳方法吗?
我收到一个对象数组:
[{json object},{json object},{json object}]
我可以使用什么最简单的代码来访问数组中的JSONObjects?
编辑:现在我想起了我用来迭代循环的方法是:
for (String row: json){
id = row.getInt("id");
name = row.getString("name");
password = row.getString("password");
}
Run Code Online (Sandbox Code Playgroud)
所以我想我已经能以某种方式将返回的Json转换为可迭代的数组.任何想法我怎么能做到这一点?
我为我的迷途道歉,但我从网上找到的一个例子中得到了这个,但后来一直无法找到它.
我刚刚开始在java中使用json.我不确定如何在JSONArray中访问字符串值.例如,我的json看起来像这样:
{
"locations": {
"record": [
{
"id": 8817,
"loc": "NEW YORK CITY"
},
{
"id": 2873,
"loc": "UNITED STATES"
},
{
"id": 1501
"loc": "NEW YORK STATE"
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
我的代码:
JSONObject req = new JSONObject(join(loadStrings(data.json),""));
JSONObject locs = req.getJSONObject("locations");
JSONArray recs = locs.getJSONArray("record");
Run Code Online (Sandbox Code Playgroud)
此时我可以访问"记录"JSONArray,但我不确定如何在for循环中获取"id"和"loc"值.对不起,如果这个描述不太清楚,我对编程有点新意.
我正在使用org.json.simple.JSONArray和org.json.simple.JSONObject.我知道,这两个类JSONArray和JSONObject是不相容的,但我仍然希望做的相当自然的事情-我想换了每一个JSONArray在每个迭代步骤一解析JSONObject(嵌套在那JSONArray).我尝试这样做:
JSONArray arr = ...; // <-- got by some procedure
for(JSONObject o: arr){
parse(o);
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译这段代码时,我确实遇到了"不兼容的类型"错误,即使它看起来很自然.所以,我的问题是迭代的最佳方法是什么JSONArray?