Reputation: 11655
I have the following JSON Content:
{
"query": {
"pages": {
"7931046": {
"pageid": 7931046,
"ns": 0,
"title": "Tang Aidi",
"revisions": [
{
"contentformat": "text/x-wiki",
"contentmodel": "wikitext",
"*": "SOME TEXT"
}
]
}
}
}
}
I try to read the "SOME TEXT" String from it.
I am stuck already when trying to read the "pages" object. I guess it should be a JSONObject but it throws me
JSONObject["pages"] not found
with following code:
JSONObject obj = new JSONObject(sEntireContent);
JSONObject oParse=(JSONObject) obj.get("query");
//JSONArray oPages=oParse.getJSONArray("pages");
>>>>>>>>>> JSONObject oPages=(JSONObject) obj.get("pages");
JSONObject firstPage=(JSONObject) oPages.get(0);
JSONObject oRevisions=(JSONObject) firstPage.get("revisions");
sWikitext=oRevisions.getString ("*");
I then firther don't know how to read a childobject, from which I don't know the name. In my example the "7931046" is a random/sequence number
Upvotes: 2
Views: 14195
Reputation: 28569
Go for relative to the parent
JSONObject oPages = oParse.getJSONObject("pages");
Upvotes: 2
Reputation: 934
If a JSONObject has one or more unknown keys as child elements, you can iterate through them like so:
JSONObject pages = obj.get("pages");
Iterator iterator = pages.keys();
while(iterator.hasNext()){
String key = (String)iterator.next();
JSONObject page = pages.getJSONObject(key);
//do stuff with the page...
}
Upvotes: 5