0
    namespace WebApplication1.Site
{
public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {


        var accessToken = "" // Token
        var client = new FacebookClient(accessToken);
        dynamic myInfo = client.Get("me/friends", new { fields = "name,id,work" });

        foreach (dynamic friend in myInfo)
        {
            foreach (dynamic work in friend.work ?? new[] { new { employer = new { name = string.Empty }, position = new { name = string.Empty } } })
                {
                    Response.Write("Employer: " + work.employer.name);
                }

        }


    }
}
}

我在第 21 行收到以下错误。我无法弄清楚是什么原因造成的。

“System.Collections.Generic.KeyValuePair”不包含“工作”的定义

来自 Facebook GraphAPI 的示例 JSON 返回。这只是前三个朋友。我正在解析近 4000 个朋友,显然这为数据结构提供了一些上下文:

    {
      "data": [
{
  "name": "Mia xxx", 
  "id": "11381", 
  "work": [
    {
      "employer": {
        "id": "100982923276720", 
        "name": "New-York Historical Society"
      }, 
      "location": {
        "id": "108424279189115", 
        "name": "New York, New York"
      }
    }
  ]
}, 
{
  "name": "Leilah xxx", 
  "id": "1133"
}, 
{
  "name": "xxx, 
  "id": "1231", 
  "work": [
    {
      "employer": {
        "id": "104362369673437", 
        "name": "Bye Bye Liver: The Philadelphia Drinking Play"
      }, 
      "location": {
        "id": "101881036520836", 
        "name": "Philadelphia, Pennsylvania"
      }, 
      "position": {
        "id": "121113421241569", 
        "name": "Actress/Bartender"
      }, 
      "description": "A sketch comedy/improv show every Saturday night at Downey's on South & Front. Come thirsty!", 
      "start_date": "2011-09"
    }, 
    {
      "employer": {
        "id": "100952634348", 
        "name": "Act II Playhouse"
      }, 
      "location": {
        "id": "109249869093538", 
        "name": "Ambler, Pennsylvania"
      }, 
      "position": {
        "id": "125578900846788", 
        "name": "My Fair Lady"
      }, 
      "description": "11 actor version of the classic musical.", 
      "start_date": "0000-00"
    }, 
4

2 回答 2

2

依赖的另一种方法dynamic是使用 JSON.net 捕获和解析 JSON,它是为查询 json 数据而设计的,并且确实比使用安全得多dynamic

http://json.codeplex.com/

并反序列化为类:

http://dotnetbyexample.blogspot.ca/2012/02/json-deserialization-with-jsonnet-class.html

于 2012-08-03T20:49:24.407 回答
2

看这个:

Response.Write("Employer: " + myInfo.work.employer.name);

我怀疑你的意思是:

Response.Write("Employer: " + work.employer.name);

这么说吧——如果这不是你的意思,你的work变量的目的是什么?

于 2012-08-03T20:30:14.287 回答