dynamic object handle problem Facebook C# sdk

青春壹個敷衍的年華 提交于 2019-12-11 05:47:18

问题


I'm using Facebook C# sdk for desktop app. I'm getting the dynamic object and then extracting the name,id etc

dynamic result = fb.Get("/me");
string name=result.name;

Now problem is I can't extract the work information or favorite teams etc. I've used the required permissions, but unable to handle the dynamic object. It's in this format:

"languages": [
{
  "id": "106502622718539", 
  "name": "Bānglā"
}, 
{
  "id": "106059522759137", 
  "name": "English"
}

],

http://developers.facebook.com/tools/explorer/

Tried and searched a lot to get them. Found nothing. I've read that it comes in the form of array. Please help to extract those information through C# code..........


回答1:


Here is a golden rule on how to consume json data in Facebook C# SDK/SimleJson (internally Facebook C# SDK uses SimpleJson for json serializing/deserializing http://simplejson.codeplex.com/).

There are 3 possible types: Array, Json Object and privimitive types.

  • Array: Can be casted to IList<Object> or IList<dynamic>
  • JsonObject: key value pair - IDictionary<string, object>
  • primitive types: bool, string, long and double.

Since langauges is an array, you can use it as IList<object> and consume it in a for loop like mentioned by Json Skeet. You also get the benefit of other IList<T> features such as indexer and different properties of the array.

dynamic result = fb.Get("/me");
var langauges = result.languages;
var length = languages.Length;
var lang1 = languages[0];
var lang1Id = lang1["id"];
var lang1Name = lang1["name"];
var lang2 = langauges[1];
var lang2Id = lang2.id;
var lang2Name = lang2.name;

since lang1 and lang2 is a JsonObject you can either use indexer like lang1["id"] as you do in for IDictionary<string,object> or much easier use lang1.id.




回答2:


It looks like you might want:

dynamic result = fb.Get("/me");
foreach (dynamic language in result.languages)
{
    Console.WriteLine("{0}: {1}", language.name, language.id);
}

Can't say I've used the Facebook SDK myself though.



来源:https://stackoverflow.com/questions/7367496/dynamic-object-handle-problem-facebook-c-sharp-sdk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!