2016-01-05 84 views
0

json響應:獲取價值觀和名稱的名稱

{ 
    "Countries": [ 

     { 

       "Country": "China", 
       "Alpha2": "CN", 
       "Alpha3": "CHN", 

       "numbers": { 
        "Jon": "100", 
        "Mat": "200", 
        "SAM": "300" 


       } 
     }, 
     { 

       "Country": "Italy", 
       "Alpha2": "IT", 
       "Alpha3": "ITA", 

       "numbers": { 
        "Benny": "400", 
        "Jack": "500" 


       } 
     } 

    ] 
} 

我的代碼:

for (int i = 0; i < m_jArry.length(); i++) { 
      JSONObject jo_inside = m_jArry.getJSONObject(i); 

      if (jo_inside.getString("Country").equals("Italy")) 
      { 
       Log.d("DTAG",jo_inside.getString("Country")); 
       Log.d("DTAG",jo_inside.getString("Alpha2")); 
       Log.d("DTAG", jo_inside.getString("Alpha3")); 

       JSONObject jo_inside2 = jo_inside.getJSONObject("numbers"); 
       Log.d("DTAG", "Size: "+jo_inside2.length()); 

       for (int j=0;j<jo_inside2.length();j++) 
       { 
        //??? 
       } 
      } 

我怎樣才能獲得的價值和他的價值的名字嗎? 對於這個例子我需要得到本尼400,傑克500

+2

我認爲這是你要搜索的內容:http://stackoverflow.com/questions/13573913/android- jsonobject-how-can-i-loop-through-a-flat-json-object-to-get-each-key-a – Blunderer

+0

這是比較複雜的文章,但它確實回答你的問題http://stackoverflow.com/questions/12870332/how-can-i-iterate-jsonobject-to-get-individual-items – Rohit5k2

回答

2

你可以通過使用json.keys獲得所有的鑰匙,在你的情況下嘗試使用下面的代碼。

Iterator<String> iter = jo_inside2.keys(); 
    while (iter.hasNext()) { 
    String key = iter.next(); 
    try { 
     Object value = jo_inside2.get(key); 
    } catch (JSONException e) { 
     //exception 
    } 
    } 
2
if (jo_inside.getString("Country").equals("Italy")) 
      { 
       Log.d("DTAG",jo_inside.getString("Country")); 
       Log.d("DTAG",jo_inside.getString("Alpha2")); 
       Log.d("DTAG", jo_inside.getString("Alpha3")); 

       JSONObject jo_inside2 = jo_inside.getJSONObject("numbers"); 
       Log.d("DTAG", "Size: "+jo_inside2.length()); 

       for (int j=0;j<jo_inside2.length();j++) 
       { 
        Iterator<?> keys = jo_inside2.keys(); 

       while(keys.hasNext()) 
        { 
        String key = (String)keys.next(); 
        if (jo_inside2.get(key) instanceof JSONObject) 
        { 
          Object value = jo_inside2.get(key); 
        } 
        } 
        } 
      } 
1

//從JSONObj

得到所有鑰匙
Iterator<String> iterator = jo_inside2.keys(); 
     while (iterator.hasNext()) { 
     String key = iterator.next(); 
     Log.i("TAG","key:"+key +"--Value::"+categoryJSONObj.optString(key); 

    } 
+0

你能接受這個答案嗎? – CodingRat

0
for(Iterator iterator = jo_inside2.keys(); iterator.hasNext();) { 
     String key = (String) iterator.next(); 
     System.out.println(key+" - "+jo_inside2.get(key)); 

     //Log.i("TAG",key +" - "+jo_inside2.get(key)); 
    }