在c#中反序列化动态对象

时间:2016-11-30 08:36:28

标签: c# asp.net-mvc facebook-graph-api

我正在尝试通过Graph API获取Facebook个人资料数据。我在MVC应用程序中使用Facebook SDK。使用以下代码返回动态结果。

dynamic myInfo = await fb.GetTaskAsync("v2.8/me?fields=first_name,last_name,link,locale,email,name,birthday,gender,location,age_range");
      var facebookProfile = new FacebookProfileViewModel()
                {
                    FirstName = myInfo.first_name,
                    LastName = myInfo.last_name,
                    LinkUrl = myInfo.link,
                    Locale = myInfo.locale };

我从Facebook获取数据 -

[{"Key":"first_name","Value":"John"},{"Key":"last_name","Value":"Doe"},{"Key":"link","Value":"https://www.facebook.com/app_scoped_user_id/4327693/"}]

我收到以下错误 -

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot implicitly convert type 'Facebook.JsonObject' to 'string'

1 个答案:

答案 0 :(得分:1)

安装newtonsoft:

Install-Package Newtonsoft.Json

从json转换:

string json = 
"[
    {
        "Key": "first_name",
        "Value": "John"
    },
    {
        "Key": "last_name",
        "Value": "Doe"
    },
    {
        "Key": "link",
        "Value": "https://www.facebook.com/app_scoped_user_id/4327693/"
    }
]";
FbProfile Profile = JsonConvert.DeserializeObject<FbProfile>(json);