我是在 C# 中使用 dynamic
关键字的新手。看起来很简单,但我似乎无法有效地使用它。
我从 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.
我想对从 Foursquare 返回的 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 字符串?
最佳答案
FacebookClient.Get
并不真正返回 JSON string。相反,它将字符串解析为一个动态对象,其属性与 JSON 字符串中的值的名称相匹配。
使用 dynamic
不会神奇地将字符串转换为具有字符串中定义的属性的对象。相反,您需要先借助 JSON.NET 等 JSON 库解析字符串。
关于c# - 解析 JSON 时使用动态关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18829758/