我刚刚开始在 java 中使用 json。我不确定如何访问 JSONArray 中的字符串值。例如,我的 json 如下所示:
{
"locations": {
"record": [
{
"id": 8817,
"loc": "NEW YORK CITY"
},
{
"id": 2873,
"loc": "UNITED STATES"
},
{
"id": 1501
"loc": "NEW YORK STATE"
}
]
}
}
my code:
JSONObject req = new JSONObject(join(loadStrings(data.json),""));
JSONObject locs = req.getJSONObject("locations");
JSONArray recs = locs.getJSONArray("record");
此时我可以访问“记录”JSONArray,但不确定如何在 for 循环中获取“id”和“loc”值。抱歉,如果这个描述不太清楚,我对编程有点陌生。
你有没有尝试过使用JSONArray.getJSONObject(int) http://json.org/javadoc/org/json/JSONArray.html#getJSONObject(int), and JSONArray.length() http://json.org/javadoc/org/json/JSONArray.html#length()创建你的for循环:
for (int i = 0; i < recs.length(); ++i) {
JSONObject rec = recs.getJSONObject(i);
int id = rec.getInt("id");
String loc = rec.getString("loc");
// ...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)