这是我来自URL的JSON数据:
[
{ "title" : "65th Issue", "author": "అశోక్"},
{ "title" : "64th Issue", "author": "రాము" },
{ "title" : "63rd Issue", "author": "శ్రీను" }
]
它看起来像JSONArray,但没有可访问的名称(数组名称)。谁能告诉我如何在android中解析此JSON数据?
解析代码
InputStream inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream);
int contentLength = connection.getContentLength();
char [] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
try{
JSONArray jArray = new JSONArray(responseData);
for(int i = 0; i < jArray.length(); i++) {
String title = jArray.getJSONObject(i).getString("title");
}
} catch (JSONException e) {
Log.v(TAG, "JSON EXCEPTION");
}
String jsonString = ...; //This contains the above mentioned String.
对于JSON字符串,[]表示数组,{}表示对象。在您的情况下,字符串以[]开头,这意味着它是一个数组,因此我们首先获取JSONArray。
JSONArray jArray = new JSONArray(jsonString);
现在,如果您看到了,则该数组具有多个以{}开头和结尾的字符串,这意味着该数组具有多个对象。因此,我们在数组长度上运行了一个循环,以提取每个对象,然后从对象中提取键值。
for(int i = 0; i < jArray.length(); i++) {
String title = jArray.getJSONObject(i).getString("title");
}
因此,完整的代码将如下所示:
String jsonString = ...; //This contains the above mentioned String.
JSONArray jArray = new JSONArray(jsonString);
for(int i = 0; i < jArray.length(); i++) {
String title = jArray.getJSONObject(i).getString("title");
}
编辑2:
String jsonString = "[\r\n { \"title\" : \"65th Issue\", \"author\": \"\u0C05\u0C36\u0C4B\u0C15\u0C4D\"},\r\n { \"title\" : \"64th Issue\", \"author\": \"\u0C30\u0C3E\u0C2E\u0C41\" },\r\n { \"title\" : \"63rd Issue\", \"author\": \"\u0C36\u0C4D\u0C30\u0C40\u0C28\u0C41\" }\r\n]";
try {
JSONArray jArray = new JSONArray(jsonString);
for (int i = 0; i < jArray.length(); i++) {
String title = jArray.getJSONObject(i).getString("title");
Log.d(LOGTAG, title);
}
} catch (JSONException e) {
e.printStackTrace();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句