我有 JSON 响应
{"as_of":"2013-04-22T19:50:41Z","trends":[{"events":null,
"query":"%23RhymeATweepsName","url":"http:\/\/twitter.com\/search?
q=%23RhymeATweepsName","promoted_content":null,
"name":"#RhymeATweepsName"},
{"events":null,"query":"%23EarthDayPK","url":
"http:\/\/twitter.com\/search?
=%23EarthDayPK","promoted_content":null,"name":
"#EarthDayPK"}],"locations":
[{"woeid":*******,"name":"********"}],"created_at":"2013-04-22T19:38:16Z"}
我正在使用以下代码解析它
jArray = new JSONArray(result);
JSONObject post = null;
for (int ii = 0; ii < jArray.length(); ii++) {
post = jArray.getJSONObject(ii);
String name = post.getJSONObject("trends").getString("name") + "\n";
}
}
但它抛出异常“JSONArray无法转换为JSONObject错误”
最佳答案
如 JSON 中所示,trends
不是 JSONObject
,而是 JSONArray
:
"trends":[
{
"events":null,
"query":"%23RhymeATweepsName",
"url":"http:\/\/twitter.com\/search? q=%23RhymeATweepsName",
"promoted_content":null,
"name":"#RhymeATweepsName"
},
{
"events":null,
"query":"%23EarthDayPK",
"url":"http:\/\/twitter.com\/search? =%23EarthDayPK",
"promoted_content":null,
"name":"#EarthDayPK"
}
]
你应该像这样解析它:
String name = post.getJSONArray("trends").getJSONObject(0).getString("name");
// or iterate... ^^
关于java - 转换时出现异常 "JSONArray cannot be converted to JSONObject error",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16155578/