JSONObject包含信息,但JSONArray获取“xxxx没有值”

时间:2014-08-20 18:50:01

标签: android json

以下是获取JSON数据的代码:

class GetFeed extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... voids) {
        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(URL_ITUNES);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
                JSONObject responseData = new JSONObject(builder.toString());
                Log.e("ItemListActivity", "responseData = " + String.valueOf(responseData));

                JSONArray test = responseData.getJSONArray("entry");
                Log.e("ItemListActivity", "test = " + String.valueOf(test.length()));

            } else {
                Log.e("ItemListActivity", "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
}

“responseData”的日志显示所有数据,但“test”的日志显示:org.json.JSONException:没有条目值。

为什么没有值进入?

我这样做是为了更好地使用JSON,使用itunes json页面获取数据:http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topgrossingapplications/sf=143441/limit=25/json

2 个答案:

答案 0 :(得分:1)

&#34;条目&#34; array不是根元素。它包含在&#34; feed&#34;对象

{
    "feed": {
        "author": {
            ...
        },
        "entry": [
            ...
        ],
        ...
    }
}   

你必须抓住&#34;饲料&#34;先对象然后拉出&#34;条目&#34;数组出来。

JSONObject feedJson = responseData.getJSONObject("feed");
JSONArray test = feedJson.getJSONArray("entry");

答案 1 :(得分:0)

尝试

JSONArray test = responseData.getJSONArray("feed");