如何解析这个维基百科的回复?

时间:2018-03-09 10:29:07

标签: android json android-json

{
    "batchcomplete": "",
    "query": {
        "pages": {
            "25675557": {
                "pageid": 25675557,
                "ns": 0,
                "title": "Cricket",
                "extract": "Cricket is a bat-and-ball game played between two teams of eleven players each on a cricket field, at the centre of which is a rectangular 22-yard-long (20 metres) pitch with a target at each end called the wicket (a set of three wooden stumps upon which two bails sit). "
            }
        }
    }
}

这是我尝试过的代码:

public void getJSON(final String city) throws JSONException {

    new AsyncTask<Void, Void, Void>() {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                URL url = new URL("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=" + city);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                BufferedReader reader =
                        new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuffer json = new StringBuffer(1024);
                String tmp = "";
                while ((tmp = reader.readLine()) != null) {
                    json.append(tmp).append("\n");
                }
                reader.close();

                data = new JSONObject(json.toString());
                if (data.getInt("cod") != 200) {
                    System.out.println("Cancelled");
                    return null;
                }

            } catch (Exception e) {
                System.out.println("Exception " + e.getMessage());
                return null;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void Void) {
            if (data != null) {
                Log.d("my weather received", data.toString());
                try {
                    //JSONObject forecastJson = new JSONObject(data);
                    JSONObject forecastArray = data.getJSONObject("query");
                    System.out.println(forecastArray);

                    JSONArray pagesArray = forecastArray.getJSONArray("pages");
                    // JSONArray idArray = pagesArray.getJSONArray(0);
                    //JSONArray idArray = pagesArray.get(0);
                    System.out.println(pagesArray);

                    JSONObject obj = pagesArray.getJSONObject(0);
                    System.out.println(obj);

                    //JSONObject weatherarray = data.getJSONObject("pages");
                    //JSONObject weather = weatherarray.getJSONObject(0);
                    // final String des = weather.getString("description");

                     /*for (int i = 0; i < forecastArray.length(); i++) {
                     JSONObject dailyForecast = forecastArray.getJSONObject(i);
                     JSONObject tempObject = dailyForecast.getJSONObject("main");
                     minTemp = tempObject.getDouble("min");
                     maxTemp = tempObject.getDouble("max");
                     //add these minTemp and maxTemp to array or the
                     //way you want to use
                 }*/
                     System.out.println("Temp Value : "+" : ");

                     runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            textvw.setText("");
                        }
                     });

                } catch (Exception e) {
                    Log.e("GetFeedTask", "Error:" + e.getMessage());
                }
            }
        }
    }.execute();
}

3 个答案:

答案 0 :(得分:2)

异常是因为响应不包含JSON数组。改变你的

JSONArray pagesArray = forecastArray.getJSONArray("pages");

JSONObject pagesArray = forecastArray.getJSONObject("pages");

我相信你正试图获得动态的密钥。您可以使用JSONObject.getKeys()来获取对象,如下所示。

Iterator keys = pagesArray.keys();

while(keys.hasNext()) {
    String dynamicKey = (String)keys.next();
    JSONObject jObj = pagesArray.getJSONObject(dynamicKey);

    //Get other attributes by jObj.getString() method.
}

尝试让我知道它是否有效。

答案 1 :(得分:0)

错误很清楚。您尝试将JSON对象分配给JSONArray

JSONArray pagesArray = forecastArray.getJSONArray("pages");

替换为

JSONObject pagesArray = forecastArray.JSONObject("pages");

JSONArray的数据介于[]而非{}之间。

答案 2 :(得分:0)

您的错误在:

        JSONArray pagesArray = forecastArray.getJSONArray("pages");

你的问题是你得到JSONArray,而页面是数据中的JsonObject。如果你的“页面”是你数据中的一个数组,你必须在[]中从服务器发送它,如下所示:

    {
"batchcomplete": "",
"query": {
    "pages": [ {
            "pageid": 25675557,
            "ns": 0,
            "title": "Cricket",
            "extract": "Cricket is a bat-and-ball game played between two teams of eleven players each on a cricket field, at the centre of which is a rectangular 22-yard-long (20 metres) pitch with a target at each end called the wicket (a set of three wooden stumps upon which two bails sit). "
        },
 {
            "pageid": 25675557,
            "ns": 0,
            "title": "Cricket",
            "extract": "Cricket is a bat-and-ball game played between two teams of eleven players each on a cricket field, at the centre of which is a rectangular 22-yard-long (20 metres) pitch with a target at each end called the wicket (a set of three wooden stumps upon which two bails sit). "
        }
    ]
}
}

并在android:

 try {
        //JSONObject forecastJson = new JSONObject(data);
        JSONObject forecastArray = data.getJSONObject("query");
        System.out.println(forecastArray);

        JSONArray pagesArray = forecastArray.getJSONArray("pages");
        System.out.println(pagesArray);


        for (int k = 0; k < pagesArray.length(); k++) {

            try {
                JSONObject object = pagesArray.getJSONObject(k);
                String pageid = object.getString("pageid");
                String ns = object.getString("ns");
                String title = object.getString("title");
                String extract = object.getString("extract");

            } catch (JSONException e) {
                e.printStackTrace();

            }
        }

    } catch (Exception e) {
        Log.e("GetFeedTask", "Error:" + e.getMessage());
    }