Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

java - How to get elements of JSONObject?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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... 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...