Wednesday, January 19, 2011

[C#] 遞迴取得多層Dictionary內的資料

這段code是以前在拉facebook資料時用的,Facebook C# SDK裡提供的JSONObject是一個由Array, Dictionary...等所組成的樹狀結構,由於取得的內容結構不定,所以只能用遞迴的方式將裡面的值拉出來,因為以後也許用的到所以貼上來記錄一下。


private void ShowDictionary(JSONObject InObj)
    {
        if (InObj.IsArray)
        {
            for (int i = 0; i < InObj.Array.Length;i++ )
            {
                ShowDictionary(InObj.Array[i]);
            }
        }
        else
        {
            foreach (KeyValuePair<string, JSONObject> item in InObj.Dictionary)
            {
                if (InObj.Dictionary[item.Key].IsDictionary)
                {
                    Console.WriteLine(string.Format("{0}: - Dictionary [", item.Key));
                    ShowDictionary(InObj.Dictionary[item.Key]);
                    Console.WriteLine("]");
                }
                else if (InObj.Dictionary[item.Key].IsArray)
                {
                    Console.WriteLine(string.Format("{0}: - Array[{1}] [", item.Key, InObj.Dictionary[item.Key].Array.Length));
                    ShowDictionary(InObj.Dictionary[item.Key]);
                    Console.WriteLine("]");
                }
                else
                {
                    Console.WriteLine(string.Format("{0}: {1}", item.Key, InObj.Dictionary[item.Key].String));
                }
            }
        }
    }
 
123

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...