Just writing
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<string object> dicSer = jss.Deserialize<dictionary object>>(json); traceDic(dicSer); } private void traceDic(Dictionary<string object> dic) { foreach (KeyValuePair<string object> 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<string object>) { textBox1.Text = textBox1.Text + p.Key + ": [{\r\n"; traceDic((Dictionary<string object>)(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 ) { traceDic((Dictionary<string object>)(al[i])); } else { MessageBox.Show("arrlist: " + al[i].GetType().ToString()); } } }</string></string></string></string></string></dictionary></string>
喜欢我的文章吗?
别忘了给点支持与赞赏,让我知道创作的路上有你陪伴。
发布评论…