在Android中使用JSON解析,我该如何解析这段代码?

时间:2014-07-13 02:26:56

标签: android json

这是来自网址的我的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");
                }

1 个答案:

答案 0 :(得分:2)

String jsonString = ...; //This contains the above mentioned String.

对于JSON String,[]表示数组,{}表示对象。在你的情况下,字符串以[]开头,表示它是一个数组,所以我们首先得到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();
    }