我正在使用使用 ASP.NET 3.5 的 Facebook C# SDK,我从此处提供的示例代码库中收到一条奇怪的错误消息: http ://www.thepcwizard.in/2013/07/sample-app -使用-facebook-c-sharp-sdk.html。此示例是使用 Facebook C# SDK 进行 FB 登录代码的基础知识的出色演练,但我有一个我似乎无法弄清楚的问题。
错误信息如下:
Server Error in '/' Application.
Unable to cast object of type 'Facebook.JsonArray' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Unable to cast object of type 'Facebook.JsonArray' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'.
Source Error:
Line 271: var athletes = (IDictionary<string, object>)me["favorite_athletes"];
Line 272:
Line 273: foreach (var athlete in (JsonArray)athletes)
我已经按照说明编译了 FB C# SDK 3.5 版,并且大部分工作正常。我不得不将动态类型替换为 var 类型并将它们转换为 IDictionary 集合,因为 ASP.NET 3.5 不支持动态类型。都好。一切都很好,包括朋友列表的生成和显示以及我所有的个人数据都被调用,但最喜欢的运动员调用导致错误(代码如下)。我认为问题在于这样一个事实,即朋友列表中有一个“数据”变量,而运动员列表没有调用这个“数据”变量。这是我所看到的如何返回 JSON 对象的唯一区别。代码示例似乎通过在检索数据时删除“数据”变量来识别这一点,但错误仍然没有运气。
从 Facebook 返回的最喜欢的运动员 JSON 数据如下:
{
"favorite_athletes": [
{
"id": "14185406833",
"name": "Serena Williams"
},
{
"id": "61801828075",
"name": "Venus Williams"
},
{
"id": "386180624733248",
"name": "Robert Griffin III"
},
{
"id": "164825930120",
"name": "Tiger Woods"
},
{
"id": "363865183112",
"name": "Floyd Mayweather"
},
{
"id": "142603419139653",
"name": "Michael Vick"
},
{
"id": "64637653943",
"name": "LeBron James"
}
],
"id": "8723497347"
}
从 Facebook 返回的朋友列表数据如下(出于此问题的目的,伪造用户信息,因为我确实有超过 4 个朋友 :)):
{
"id": "8723497347",
"friends": {
"data": [
{
"name": "Friend 1",
"id": "1234567"
},
{
"name": "Friend 2",
"id": "567965"
},
{
"name": "Friend 3",
"id": "9847634"
},
{
"name": "Friend 4",
"id": "100005000106091"
}
],
"paging": {
"next": "https://graph.facebook.com/8723497347/friends?limit=5000&offset=5000&__after_id=100005000106091"
}
}
}
引发错误的代码块如下:
private void GetUserData(string accessToken)
{
var fb = new FacebookClient(accessToken);
var me = (IDictionary<string, object>)fb.Get("me?fields=friends,name,email,favorite_athletes");
string id = (string)me["id"]; // Store in database
string email = (string)me["email"]; // Store in database
string FBName = (string)me["name"]; // Store in database
NameText.Visible = true;
NameText.Text = FBName;
ViewState["FBName"] = FBName; // Storing User's Name in ViewState
var friends = (IDictionary<string, object>)me["friends"];
foreach (var friend in (JsonArray)friends["data"])
{
ListItem item = new ListItem((string)(((JsonObject)friend)["name"]), (string)(((JsonObject)friend)["id"]));
FriendList.Items.Add(item);
}
var athletes = (IDictionary<string, object>)me["favorite_athletes"];
foreach (var athlete in (JsonArray)athletes)
{
SportsPersonList.Items.Add((string)(((JsonObject)athlete)["name"]));
}
Login.Text = "Log Out";
}
对此的任何建议将不胜感激!在此先感谢您的时间。