Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何解析数组之类的JSON数据-->;对象-->;有价值的对象_Java_Android_Json - Fatal编程技术网

Java 如何解析数组之类的JSON数据-->;对象-->;有价值的对象

Java 如何解析数组之类的JSON数据-->;对象-->;有价值的对象,java,android,json,Java,Android,Json,我是android开发新手。我只是对JSON知之甚少。我使用Json简单格式 { "worldpopulation": [ { "rank":1,"country":"China", "population":"1,354,040,000", "flag":"http://www.androidbegin.com/tutorial/flag/china.png" }, { "rank":

我是android开发新手。我只是对JSON知之甚少。我使用Json简单格式

{

"worldpopulation": 
[
     {
         "rank":1,"country":"China",
         "population":"1,354,040,000",
         "flag":"http://www.androidbegin.com/tutorial/flag/china.png"
     }, 

     {
         "rank":2,"country":"India",
         "population":"1,210,193,422",
         "flag":"http://www.androidbegin.com/tutorial/flag/india.png"
     }
  ]
}
在上面的JSON数据中,我们可以在获得JSON数组worldpopulation后简单地调用rank、country

现在我有了下面显示的JSON数据,这里的JSON数组是相同的,我想因为该项存在,我不知道。然后它有对象作为数字,它有国家

{  
"Items":"0 to 2",
"worldpopulation":[  
  {  
     "0":{  
        "country":"China",
            "population":"1,354,040,000",
            "flag":"http://www.androidbegin.com/tutorial/flag/china.png"
     }
  },
  {  
     "1":{  
        "country":"India",
            "population":"1,210,193,422",
             "flag":"http://www.androidbegin.com/tutorial/flag/india.png"
     }
  }
 ]
}
现在我不知道如何称呼国家、人口和国旗

这和我们的方法一样吗。getstring(“rank”);在jsonarray之后(“世界人口”)

或不同。

按以下步骤操作

try {
    JSONObject reader = new JSONObject("your json str");

    JSONArray items = reader.getJSONArray("worldpopulation");
    for (int i = 0; i < items.length(); ++i) {
        JSONObject jsonProgram = items.getJSONObject(i);
        JSONObject yourObject = null;
        if (i == 0) {
            yourObject = jsonProgram.getJSONObject("0");
        } else {
            yourObject = jsonProgram.getJSONObject("1");
        }

        //Do here what did before with yourObject

    }
} catch (JSONException e) {
    Log.i("Test", e.toString());
}
试试看{
JSONObject reader=新的JSONObject(“您的json str”);
JSONArray items=reader.getJSONArray(“世界人口”);
对于(int i=0;i
看起来不错,但您可能希望使用
optJSONArray()
optJSONObject()
而不是将其全部包装在try/catch块中。如果您试图获取的项分别不是JSONArray或JSONObject,则两者都返回null。我同意optFunction类比,如果找不到它们,它们将返回null,但新的JSONObject()仍会抛出exeption