8

I have a JSONObject that contains some JSONObjects as follows:

"statistics": {
    "John": {
      "Age": "22",
      "status": "married"
    },
    "Ross": {
      "Age": "34",
      "status": "divorced"
    }
 }

Now all I know is the object name(statistics), and don't know it's elements number or it's elements names , So, is there's a way to parse that Object so that I can get it's elements and deal with it (ie. John, Ross) ?

Muhammed Refaat
  • 8,564
  • 12
  • 81
  • 114

2 Answers2

17
JSONObject json = new JSONObject(yourdata);
String statistics = json.getString("statistics");
JSONObject name1 = json.getJSONObject("John");
String ageJohn = name1.getString("Age");

For getting those items in a dynamic way:

JSONObject json = new JSONObject(yourdata);
String statistics = json.getString("statistics");

for (Iterator key=json.keys();key.hasNext();) {
    JSONObject name = json.get(key.next());
    //now name contains the firstname, and so on... 
}
Mat
  • 1,320
  • 1
  • 19
  • 36
Emanuel S
  • 7,809
  • 2
  • 34
  • 51
  • well, that works and gives me the contained Objects each, but how to get the Names of these objects? – Muhammed Refaat Jun 18 '14 at 08:12
  • Yes. As displayed in the example. String key = key.next(); JSONObject name = json.get(key); Log.d("data", "key="+key+ " and value="+json.toString()); – Emanuel S Jun 18 '14 at 08:13
  • i got error: `Error:(65, 48) java: incompatible type: java.lang.Object cannot be casted to java.lang.String` – Lei Yang May 07 '19 at 10:17
2

You did not specify which library you intend to use to represent the JSON object. Usually there are methods to enumerate the properties of the object. For example:

org.json.JSONObject.keys()

returns an iterator of the String names in the object.

Henry
  • 41,816
  • 6
  • 58
  • 77