C# ~ parse JSON to dynamic object

這範例是抓取youtube影片的資訊

透過youtube api提供的json來解析取得想要的data

這邊是直接把json轉成dynamic

個人比較喜歡這樣....因為我真的搞不懂.net的Dictionary還是甚麼List的0rz

dynamic寫法就很像php

反正你知道他的json長甚麼樣子再下去寫就好

也不用為此創一個物件去弄些543麻煩要命

所以我討厭寫.net.......php這邊只要json_decode($xxx)就可以把他轉成陣列

真的不用幾秒的時間....

c#這邊則是要透過一堆物件做些奇奇怪怪的事才完成

雖然人家物件導向比較屌.....

但我就是懶....還是prefer用php簡單coding就可達成所要的結果

---------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string url = "http://gdata.youtube.com/feeds/api/videos/UlNO5CpVbhk?v=2&alt=json";
var webRequest = WebRequest.Create(url);
using (var response = webRequest.GetResponse())
using (var content = response.GetResponseStream())
using (var reader = new StreamReader(content))
{
var strContent = reader.ReadToEnd();
JavaScriptSerializer jss = new JavaScriptSerializer();
dynamic d = jss.Deserialize<dynamic>(strContent);
Label1.Text = d["entry"]["yt$statistics"]["viewCount"].ToString();
}
}
}

---------------------------------------------------------

沒有留言: