Java 如何获取 JSONObject 的元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24279958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:16:09  来源:igfitidea点击:

How to get elements of JSONObject?

javajson

提问by Muhammed Refaat

I have a JSONObjectthat contains some JSONObjectsas follows:

我有一个JSONObject包含JSONObjects以下内容的:

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

Now all I know is the object name(statistics), and don't knowit's elements numberor 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) ?

现在我只知道对象名称(统计数据),不知道它的元素编号元素名称,所以,有没有办法解析该对象,以便我可以获取它的元素并处理它(即约翰,罗斯)?

采纳答案by Emanuel S

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... 
}

回答by Henry

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:

您没有指定打算使用哪个库来表示 JSON 对象。通常有枚举对象属性的方法。例如:

org.json.JSONObject.keys()

returns an iterator of the String names in the object.

返回对象中字符串名称的迭代器。