1
{
    "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). "
            }
        }
    }
}

this is the code I tried :

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();
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • 6
    Possible duplicate of [How to parse JSON in Android](https://stackoverflow.com/questions/9605913/how-to-parse-json-in-android) – AskNilesh Mar 09 '18 at 10:31
  • 1
    what's the issue? – Alessandro.Vegna Mar 09 '18 at 10:31
  • Can't you use Gson to simplify your parsing ? – An-droid Mar 09 '18 at 10:32
  • 03-09 16:02:38.501 11672-11672/com.example.a25100059.wikipedia E/GetFeedTask: Error:Value {"45139":{"pageid":45139,"ns":0,"title":"Chennai","extract":"Chennai ( ( listen); formerly known as Madras ( listen) or ) is the capital of the Indian state of Tamil Nadu. Located on the Coromandel Coast off the Bay of Bengal, it is one of the biggest cultural, economic and educational centres in South India. Aission."}} at pages of type org.json.JSONObject cannot be converted to JSONArray – Komal Gupta Mar 09 '18 at 10:33
  • this is the error i am getting. "pages of type org.json.JSONObject cannot be converted to JSONArray" – Komal Gupta Mar 09 '18 at 10:34
  • 2
    it says "pages" is not a JSONArray but it is a JSONObject. – SripadRaj Mar 09 '18 at 10:36
  • i need just extract to be displayed. – Komal Gupta Mar 09 '18 at 10:37
  • {"batchcomplete":"","query":{"pages":{"25675557":{"pageid":25675557,"ns":0,"title":"Cricket","extract":"Cricket........"}}}} The problem is i need to access extract object but inside the pages object id is given and id is different for each search.. so please tell me how to access extract. – Komal Gupta Mar 09 '18 at 10:38
  • Just use GSON, please. – Tiago Dávila Mar 09 '18 at 10:40
  • see.. this id 25675557 is different for each search. In my code city is a variable and it will take value from my textview that i will enter and search it.. for each search id will be different so how we will going to access extract. ,"query":{"pages":{"25675557":{"pageid":25675557,"ns":0,"title":"Cricket","extract":"Cricket........"}}}} – Komal Gupta Mar 09 '18 at 11:04
  • please help me.. – Komal Gupta Mar 09 '18 at 11:06
  • i don't have any idea about GSON. – Komal Gupta Mar 09 '18 at 11:07
  • because you have different page name and size you must send your array in [] – Aslami.dev Mar 11 '18 at 05:39

3 Answers3

2

The exception is because the response does not contain JSON Array. Change your

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

to

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

and I believe that you're trying to get keys which are dynamic. You cloud get the objects using JSONObject.getKeys() like below.

Iterator keys = pagesArray.keys();

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

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

Try and let me know if it works.

SripadRaj
  • 1,687
  • 2
  • 22
  • 33
  • while(keys.hasNext()) { String dynamicKey = (String)keys.next(); JSONObject jObj = pagesArray.getJSONObject(dynamicKey); final JSONObject sobj = jObj.getJSONObject("extract"); System.out.println(sobj); final String des = sobj.getString("extract"); System.out.println("Temp Value : " +sobj ); – Komal Gupta Mar 09 '18 at 11:30
  • Thank you sir.. I got my answer. – Komal Gupta Mar 09 '18 at 11:48
  • @KomalGupta did my answer help you? Please accept if it did :) – SripadRaj Mar 09 '18 at 11:55
0

The error is clear enough. you try to assign a JSONobject to a JSONArray

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

Replace by

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

the data of a JSONArray are between [] and not {}.

kfir88
  • 380
  • 2
  • 16
  • "pages": { "25675557": { "pageid": 25675557, "ns": 0, "title": "Cricket", "extract"...................."}}} the id is different for each search . so how i will access extract. – Komal Gupta Mar 09 '18 at 11:38
  • you know the id in advance before starting to parse? – kfir88 Mar 09 '18 at 11:51
0

your error is in :

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

Your problem is that you getJSONArray while pages are a JsonObject in your data .if your "pages" is a array in your data you must send it in [] from server like this:

    {
"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). "
        }
    ]
}
}

and in 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());
    }
Aslami.dev
  • 880
  • 8
  • 19