C# 處理 facebook JSON Serialized Data

當透過 access token 去 facebook 抓取資料時,回傳的資料將以 JSON 的方式編碼,在 C# 裡頭可以用 JavaScriptSerializer 來處理,下面是個很懶惰的處理方式,不需要另外先去設計與宣告一個符合 facebook JSON 格式的 class object 來儲存資料,反正需要的時候再來針對 Key 另外處理即可。

using System.Web.Script.Serialization;
using System.Collections;
using System.IO;

private void ProcessFBJSON()
{
    JavaScriptSerializer jss = new JavaScriptSerializer();

    string json;

    StreamReader sr = new StreamReader(@"C:\file.txt", Encoding.Default);
    json = sr.ReadToEnd();
    sr.Close();

    Dictionary dicSer = jss.Deserialize>(json);

    traceDic(dicSer);
}

private void traceDic(Dictionary dic)
{
    foreach (KeyValuePair p in dic)
    {
        if (p.Value is String)
        {
            textBox1.Text = textBox1.Text + p.Key + ": " + p.Value + "\r\n";
        }
        else if (p.Value is ArrayList)
        {
            textBox1.Text = textBox1.Text + p.Key + ": {\r\n";
            traceArrayList((ArrayList)(p.Value));
            textBox1.Text = textBox1.Text + "}\r\n";
        }
        else if (p.Value is Dictionary)
        {
            textBox1.Text = textBox1.Text + p.Key + ": [{\r\n";
            traceDic((Dictionary)(p.Value));
            textBox1.Text = textBox1.Text + "}]\r\n";
        }
        else if (p.Value is int || p.Value is float || p.Value is double)
        {
            textBox1.Text = textBox1.Text + p.Key + ": " + p.Value.ToString() + "\r\n";
        }
        else
        {
            MessageBox.Show("dictionary: " + p.Value.GetType().ToString());
        }
    }
}

private void traceArrayList(ArrayList al)
{
    for (int i = 0; i < al.Count; i++)
    {
        if (al[i] is String)
        {
            textBox1.Text = textBox1.Text + "   " + al[i].ToString() + "\r\n";
        }
        else if (al[i] is Dictionary)
        {
            traceDic((Dictionary)(al[i]));
        }
        else
        {
            MessageBox.Show("arrlist: " + al[i].GetType().ToString());
        }
    }
}