I am trying read JSON data from this link.
I am able to read the entire data inside pages attribute using :
JSONObject data=(JSONObject)new JSONTokener(IOUtils.toString(new URL("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Russell%27s_paradox"))).nextValue();
String pageName=data.getJSONObject("query").getString("pages");
System.out.println(pageName);
I want to get the data from "extract" attribute next from the above mentioned link, which I am unable to. I am new with this and I can't find any resources to learn this.
I tried the following code but I am getting a JSONException.
JSONArray arr=data.getJSONArray("pages");
for(int i=0;i<arr.length();i++){
String def=arr.getJSONObject(i).getString("extract");
System.out.println(def);
}
Help.
The structure of the JSON you're trying to parse is this:
{
"batchcomplete": "",
"query": {
"normalized": [
{
"from": "Russell's_paradox",
"to": "Russell's paradox"
}
],
"pages": {
"46095": {
"pageid": 46095,
"ns": 0,
"title": "Russell's paradox",
"extract": "..."
}
That is, pages
inside query
is an object, not an array.
And then, extract
is within another nested object, with key 46095
.
You can get to the extract
field like this:
JSONObject pages = data.getJSONObject("query").getJSONObject("pages");
for (String key : pages.keySet()) {
String def = pages.getJSONObject(key).getString("extract");
System.out.println(def);
}