如何迭代JSON对象并获取属性

时间:2015-04-26 15:48:30

标签: c# unity3d

在Unity中,我需要使用the simple JSON Parser / builder

迭代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"
      }
   }
}

你会怎么做?

1 个答案:

答案 0 :(得分:3)

我自己找到了解决方案:返回私有变量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]);
}