Nick
Nick

Reputation: 9373

Android: Json get inner object

I'm trying to get the inner object of a json array (my jargon could be incorrect) that looks like this:

{
"News": {
    "0": {
        "name": "nytimes",
        "fullName": "The New York Times",
        "text": "@OwenPerry We heard from the owner of the house and corrected the article http://t.co/8GEgGy7",
        "timestamp": "2011-08-15 12:20:36"
    },
    "1": {
        "name": "HuffingtonPost",
        "fullName": "Huffington Post",
        "text": "Look out! New Zealand Skier chased by angry bulls - http://t.co/L0PZkx4",
        "timestamp": "2011-08-15 12:19:04"
    }
}
}

My code to retrieve the inner objects looks like this:

        JSONArray category = json.getJSONArray("News");
        JSONArray innerobj = category.getJSONArray(0);
        for (int i = 0; i < innerobj.length(); i++) {
            HashMap<String, String> map = new HashMap<String, String>();
            JSONObject c = innerobj.getJSONObject(i);

            map.put("id", String.valueOf(i));
            map.put("name", c.getString("fullName") + "\n(#"
                    + c.getString("name") + ") ");
            map.put("text",
                    c.getString("text") + "\n - "
                            + c.getString("timestamp"));
            mylist.add(map);
        }

Any Ideas on what i'm doing incorrectly?

Upvotes: 1

Views: 1209

Answers (1)

MByD
MByD

Reputation: 137352

You don't have JSONArray, but JSONObjects. Your JSONObject structure is:

  1. Main JSONObject, which contains 1 JSONObject - "news"
  2. "news" contains two JSONObjects, "0" and "1"
  3. Each of those objects have four fields - "name", "fullname", "text" and "timestamp"

Consider:

JSONObject jobj = new JSONObject(yourString);
JSONObject newsobj = jobj.getJSONObject("news");
JSONObject firstOne = newsobj.getJSONObject("0"); // this is the object "0"
....

Upvotes: 3

Related Questions