【问题标题】:How to Parse JSON Data like array-->Object-->Object with value如何解析 JSON 数据,如数组--> 对象--> 带有值的对象
【发布时间】:2015-10-15 19:09:47
【问题描述】:

我是安卓开发新手。我对 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"
     }
  }
 ]
}

现在我不知道如何称呼国家、人口和国旗。

方法一样吗。 Jsonobject.getstring("rank");在 jsonarray("worldpopulation");

之后

或者不同。

【问题讨论】:

    标签: java android json


    【解决方案1】:

    如下操作

    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());
    }
    

    【讨论】:

    • 看起来不错,但您可能希望使用 optJSONArray()optJSONObject() 而不是将它们全部包装在 try/catch 块中。如果您尝试获取的项目分别不是 JSONArray 或 JSONObject,则两者都返回 null。
    • 我同意 optFunction 类似物,如果没有找到它们会返回 null 但 new JSONObject() 仍然会抛出异常
    猜你喜欢
    • 1970-01-01
    • 2019-12-01
    • 2019-01-14
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多