2013-09-16 72 views
1

我是新手在C#中使用dynamic關鍵字。這似乎很簡單,但我似乎無法有效地使用它。解析JSON時使用動態關鍵字

我看到來自Facebook這個例子:

var client = new FacebookClient(); 
dynamic me = client.Get("totten"); 
string firstname = me.first_name; 

它工作正常,但如果你在調試器看me,那麼你就可以看到client.Get()回報簡單的JSON。同它的Facebook的文件中說:

The result of this request is a dynamic object containing various properties such as first_name, last_name, user name, etc. You can see the values of this request by browsing to http://graph.facebook.com/totten in your web browser. The JSON result is shown below.

我想從四方與返回的JSON做同樣的閃避:

private static string GetReturnedUrlFromHttp(string url) 
{ 
    HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; 
    webRequest.Timeout = 10000; 
    webRequest.Method = "GET"; 
    WebResponse response = webRequest.GetResponse(); 

    string responseStr = String.Empty; 

    using (var stream = response.GetResponseStream()) 
    { 
     var r = new StreamReader(stream); 
     responseStr = r.ReadToEnd(); 
    } 

    return responseStr; 
} 

public static void FillDataFromFoursquareUsingDynamic() 
{ 
    string foursquare_url_detail = "https://api.foursquare.com/v2/venues/4b80718df964a520e57230e3?locale=en&client_id=XXX&client_secret=YYY&v=10102013"; 
    dynamic responseStr = GetReturnedUrlFromHttp(foursquare_url_detail); 
    var response = responseStr.response; 
} 

我得到了以下錯誤:

'string' does not contain a definition for 'response'

爲什麼我我得到這個錯誤,是否有可能'解析'任何像Facebook一樣的JSON字符串?

回答

6

FacebookClient.Get並不真正返回JSON 字符串。相反,它會將字符串解析爲一個動態對象,其屬性與JSON字符串中的值的名稱相匹配。

使用dynamic不會奇蹟般地將字符串轉換爲具有在字符串中定義的屬性的對象。相反,您需要先使用JSON.NET等JSON庫的幫助來解析字符串。