问题
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