2015-10-15 50 views
1

我是Android開發新手。我對JSON知之甚少。我用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數組世界人口後簡單地調用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( 「等級」);在jsonarray(「世界人口」)之後;

或者不同。而不是包裝這一切在一個try/catch塊

回答

3

請執行以下

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

看起來不錯,但您可能需要使用'optJSONArray()'和'optJSONObject()'。如果您試圖獲取的項目不是JSONArray或JSONObject,則兩者都返回null。 –

+1

我同意optFunction類似物,如果沒有找到,它們返回null,但是新的JSONObject()仍然會拋出異常 –