简体   繁体   中英

C# Facebook SDK dynamic data conversion

I got an Object from Facebook SDK

var responsePages = (JsonObject)FBClient_.Get(new { ids = 
[123123123, 123123123, 12312213, etc]});

This query returns data (see image)

结果

Now how do I convert this into a list of objects? I have tried following but it does not work

var pe = (from dynamic page
                in (IList<object>)(object)responsePages.Values
                             orderby page.name ascending
                             select new FBPage
                             {
                                 Id = Convert.ToString(page.id),
                             }
                ).ToList();

So that failed, would appreciate any help because this dynamic stuff drives me seriously mad.

Thanks

You don't need to cast if you are using dynamic.

var fb = new FacebookClient();

dynamic result = fb.Get(new { ids = new[] { "...", "..." } });

var pages = new List<FBPage>();
foreach (var page in result.Values)
{
    var fbPage = new FBPage {
        Id = page.id,
        Name = page.name
    };

    pages.Add(fbPage);
}

or if you want to use linq. (extension methods are not supported for dynamic, so you will need to do some casting, JsonObject => IDictionary<string, dyanmic> , JsonArray => IList<dynamic> )

var pages = ((IDictionary<string, dynamic>)result)
    .Select(kpv => kpv.Value)
    .Select(p => new FBPage { id = p.id, name = p.name })
    .ToList();

Or you strongly typed classes.

var fbPages = fb.Get<IDictionary<string, FBPage>>(new { 
    ids = new[] { "...", "..." } 
}).Values;

public class FBPage
{
    public string id { get; set; }
    public string name { get; set; }
}

'responsePages.Values' is an ICollection<JsonValue>

JsonValues can be serialized to Json strings, which can then be made the play things of a good Json deserializer such as Json.Net.

Using a simple loop this might look something like:

List<dynamic> dynamicList = new List<dynamic>();
List<FBPage> pe = new List<FBPage>();

foreach(var page in responsePages.Values)
{
   //ToString is overridden in JsonValue to provide a string in Json format
   string pageAsJsonString = page.ToString();

   //Deserialize (parse) to a dynamic object using Json.Net's JObject.Parse static method
   dynamic parsedPage = JObject.Parse(pageAsJsonString);
   dynamicList.Add(parsedPage);

   //Alternatively, if you have an appropriate object handy, deserialize directly:
   FBPage deserializedPage = JsonConvert.DeserializeObject<FBPage>(pageAsJsonString);
   pe.Add(deserializedPage);
}

foreach(dynamic page in dynamicList)
{
   Console.WriteLine(page.name);
}

foreach(FBPage page in pe)
{
   Console.WriteLine(page.Id);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM