Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get elements of JSONObject?

Tags:

java

json

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) ?

like image 899
Muhammed Refaat Avatar asked Jun 18 '14 07:06

Muhammed Refaat


1 Answers

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... 
}
like image 129
Emanuel S Avatar answered Oct 04 '22 18:10

Emanuel S