2015-04-26 79 views
2

在Unity,我需要使用the simple JSON Parser/builder如何遍歷一個JSON對象,並獲取屬性

遍歷JSON對象我通過JSONNode node = JSON.Parse(result);有這樣的JSONNode。

這裏是我得到的JSON(當然它會發生很大的變化隨着時間的推移,它可能有更多或更少的屬性):

{ 
    "Nîddûrdy":{ 
     "nb_players":"2", 
     "width":"20", 
     "height":"20", 
     "ships":{ 
     "aircraft_carrier":"10", 
     "battleship":"0", 
     "destroyer":"0", 
     "submarine":"0", 
     "torpilleur":"1" 
     } 
    }, 
    "Embers":{ 
     "nb_players":"2", 
     "width":"3", 
     "height":"2", 
     "ships":{ 
     "aircraft_carrier":"0", 
     "battleship":"0", 
     "destroyer":"0", 
     "submarine":"0", 
     "torpilleur":"1" 
     } 
    }, 
    "Omyctudo":{ 
     "nb_players":"2", 
     "width":"3", 
     "height":"2", 
     "ships":{ 
     "aircraft_carrier":"0", 
     "battleship":"0", 
     "destroyer":"0", 
     "submarine":"0", 
     "torpilleur":"1" 
     } 
    } 
} 

你會如何做?

+0

你的意思_iterating了在dictionary_的KeyValuePairs? – stefankmitph

+0

是的,我會更新我的問題 –

+0

我從來沒有使用SimpleJson和Unity,但這似乎回答你的問題:http://answers.unity3d.com/questions/648066/how-to-get-the-密鑰對的一-字典的.html – stefankmitph

回答

2

我自己找到了解決方案:返回私有變量m_Dict的鍵。修改SimpleJSON.cs並添加此屬性:

public class JSONClass : JSONNode, IEnumerable 
{ 
    public Dictionary<string, JSONNode>.KeyCollection keys 
    { 
     get { 
      return m_Dict.Keys; 
     } 
    } 
} 

然後一個基本的循環:

JSONClass j = (JSONClass)objJSON.AsObject ["games"]; 
foreach (string k in j.keys){ 
    Debug.Log (k); 
    Debug.Log (j[k]); 
}