如何使用Yahoo Api的索引解析JSON数组

时间:2019-06-21 15:35:14

标签: c# json json.net

鉴于Yahoo API的响应,我试图使用Newtonsoft.Json和ASP.NET / C#将播放器解析出来。我还想最后检查count的值。

{
  "fantasy_content": {
    "xml:lang": "en-US",
    "yahoo:uri": "/fantasy/v2/game/nfl/players",
    "game": [
      {
        "game_key": "390",
        "game_id": "390",
        "name": "Football",
        "code": "nfl",
        "type": "full",
        "url": "https://football.fantasysports.yahoo.com/f1",
        "season": "2019",
        "is_registration_over": 0,
        "is_game_over": 0,
        "is_offseason": 0
      },
      {
        "players": {
          "0": {
            "player": [
              [
                {
                  "player_key": "390.p.30972"
                },
                {
                  "player_id": "30972"
                },
                {
                  "name": {
                    "full": "Saquon Barkley",
                    "first": "Saquon",
                    "last": "Barkley",
                    "ascii_first": "Saquon",
                    "ascii_last": "Barkley"
                  }
                },
                {
                  "editorial_player_key": "nfl.p.30972"
                },
                {
                  "editorial_team_key": "nfl.t.19"
                },
                {
                  "editorial_team_full_name": "New York Giants"
                },
                {
                  "editorial_team_abbr": "NYG"
                },
                {
                  "bye_weeks": {
                    "week": "11"
                  }
                },
                {
                  "uniform_number": "26"
                },
                {
                  "display_position": "RB"
                },
                {
                  "headshot": {
                    "url": "https://s.yimg.com/iu/api/res/1.2/RtPm7fdFHthz1._DrpkAqA--~C/YXBwaWQ9eXNwb3J0cztjaD0yMzM2O2NyPTE7Y3c9MTc5MDtkeD04NTc7ZHk9MDtmaT11bGNyb3A7aD02MDtxPTEwMDt3PTQ2/https://s.yimg.com/xe/i/us/sp/v/nfl_cutout/players_l/09242018/30972.png",
                    "size": "small"
                  },
                  "image_url": "https://s.yimg.com/iu/api/res/1.2/RtPm7fdFHthz1._DrpkAqA--~C/YXBwaWQ9eXNwb3J0cztjaD0yMzM2O2NyPTE7Y3c9MTc5MDtkeD04NTc7ZHk9MDtmaT11bGNyb3A7aD02MDtxPTEwMDt3PTQ2/https://s.yimg.com/xe/i/us/sp/v/nfl_cutout/players_l/09242018/30972.png"
                },
                {
                  "is_undroppable": "0"
                },
                {
                  "position_type": "O"
                },
                [],
                {
                  "eligible_positions": [
                    {
                      "position": "RB"
                    }
                  ]
                },
                [],
                [],
                []
              ]
            ]
          },
          "1": {
            "player": [
              [
                {
                  "player_key": "390.p.29238"
                },
                {
                  "player_id": "29238"
                },
                {
                  "name": {
                    "full": "Ezekiel Elliott",
                    "first": "Ezekiel",
                    "last": "Elliott",
                    "ascii_first": "Ezekiel",
                    "ascii_last": "Elliott"
                  }
                },
                {
                  "editorial_player_key": "nfl.p.29238"
                },
                {
                  "editorial_team_key": "nfl.t.6"
                },
                {
                  "editorial_team_full_name": "Dallas Cowboys"
                },
                {
                  "editorial_team_abbr": "Dal"
                },
                {
                  "bye_weeks": {
                    "week": "8"
                  }
                },
                {
                  "uniform_number": "21"
                },
                {
                  "display_position": "RB"
                },
                {
                  "headshot": {
                    "url": "https://s.yimg.com/iu/api/res/1.2/.0ocryeNkGmnFWlYOhT4hw--~C/YXBwaWQ9eXNwb3J0cztjaD0yMzM2O2NyPTE7Y3c9MTc5MDtkeD04NTc7ZHk9MDtmaT11bGNyb3A7aD02MDtxPTEwMDt3PTQ2/https://s.yimg.com/xe/i/us/sp/v/nfl_cutout/players_l/09272018/29238.png",
                    "size": "small"
                  },
                  "image_url": "https://s.yimg.com/iu/api/res/1.2/.0ocryeNkGmnFWlYOhT4hw--~C/YXBwaWQ9eXNwb3J0cztjaD0yMzM2O2NyPTE7Y3c9MTc5MDtkeD04NTc7ZHk9MDtmaT11bGNyb3A7aD02MDtxPTEwMDt3PTQ2/https://s.yimg.com/xe/i/us/sp/v/nfl_cutout/players_l/09272018/29238.png"
                },
                {
                  "is_undroppable": "0"
                },
                {
                  "position_type": "O"
                },
                [],
                {
                  "eligible_positions": [
                    {
                      "position": "RB"
                    }
                  ]
                },
                [],
                [],
                []
              ]
            ]
          },
          "2": {
            "player": [
              [
                {
                  "player_key": "390.p.30180"
                },
                {
                  "player_id": "30180"
                },
                {
                  "name": {
                    "full": "Alvin Kamara",
                    "first": "Alvin",
                    "last": "Kamara",
                    "ascii_first": "Alvin",
                    "ascii_last": "Kamara"
                  }
                },
                {
                  "editorial_player_key": "nfl.p.30180"
                },
                {
                  "editorial_team_key": "nfl.t.18"
                },
                {
                  "editorial_team_full_name": "New Orleans Saints"
                },
                {
                  "editorial_team_abbr": "NO"
                },
                {
                  "bye_weeks": {
                    "week": "9"
                  }
                },
                {
                  "uniform_number": "41"
                },
                {
                  "display_position": "RB"
                },
                {
                  "headshot": {
                    "url": "https://s.yimg.com/iu/api/res/1.2/loANJKjPdmUu1gM1jyKK1A--~C/YXBwaWQ9eXNwb3J0cztjaD0yMzM2O2NyPTE7Y3c9MTc5MDtkeD04NTc7ZHk9MDtmaT11bGNyb3A7aD02MDtxPTEwMDt3PTQ2/https://s.yimg.com/xe/i/us/sp/v/nfl_cutout/players_l/08252018/30180.png",
                    "size": "small"
                  },
                  "image_url": "https://s.yimg.com/iu/api/res/1.2/loANJKjPdmUu1gM1jyKK1A--~C/YXBwaWQ9eXNwb3J0cztjaD0yMzM2O2NyPTE7Y3c9MTc5MDtkeD04NTc7ZHk9MDtmaT11bGNyb3A7aD02MDtxPTEwMDt3PTQ2/https://s.yimg.com/xe/i/us/sp/v/nfl_cutout/players_l/08252018/30180.png"
                },
                {
                  "is_undroppable": "0"
                },
                {
                  "position_type": "O"
                },
                [],
                {
                  "eligible_positions": [
                    {
                      "position": "RB"
                    }
                  ]
                },
                [],
                [],
                []
              ]
            ]
          },
          "count": 3
        }
      }
    ],
    "time": "181.84494972229ms",
    "copyright": "Data provided by Yahoo! and STATS, LLC",
    "refresh_rate": "60"
  }
}

有两件事让我失望。

  1. game是一个看起来很奇怪的数组,并且
  2. 每个玩家前面都有一个索引,例如

    0: { player: { //dah dah dah }

如果索引不存在,我可能会使用类似的方法找出它:

var jObject = JObject.Parse(await response.Content.ReadAsStringAsync());
if (jObject.ContainsKey("players"))
{
    var yPs = jObject["players"].ToObject<YahooPlayerListJson>();
    yPlayerList.AddRange(yPs.YPlayers);
    if(yPs.Count < 25) { f = 5000; }
}

但是索引给我带来了困难。如何解析此JSON?

1 个答案:

答案 0 :(得分:2)

U,这是一种非常糟糕的JSON格式。异构数组使使用它特别困难。在我看来,这些数据是从XML转换而来的(非常糟糕)。如果是这样,直接使用XML可能会更直接。无论如何,我们都可以使它工作。这就是我要采取的方法。

  1. 制作一些类来捕获您感兴趣的播放器数据:

    public class Player
    {
        public string PlayerKey { get; set; }
        public string PlayerId { get; set; }
        public Name Name { get; set; }
        public string EditorialPlayerKey { get; set; }
        public string EditorialTeamKey { get; set; }
        public string EditorialTeamFullName { get; set; }
        public string EditorialTeamAbbr { get; set; }
        public Week ByeWeeks { get; set; }
        public string UniformNumber { get; set; }
        public string DisplayPosition { get; set; }
        public Photo Headshot { get; set; }
        public string ImageUrl { get; set; }
        public string IsUndroppable { get; set; }
        public string PositionType { get; set; }
        public Position[] EligiblePositions { get; set; }
    }
    
    public class Name
    {
        public string Full { get; set; }
        public string First { get; set; }
        public string Last { get; set; }
    }
    
    public class Photo
    {
        public string Url { get; set; }
        public string Size { get; set; }
    }
    
    public class Week
    {
        [JsonProperty("week")]
        public int Number { get; set; }
    }
    
    public class Position
    {
        [JsonProperty("position")]
        public string Name { get; set; }
    }
    
  2. 设置配置有SnakeCaseNamingStrategy的串行器。这将处理JSON中的snake_case属性名称到C#类中的ProperCase属性名称的转换。

    JsonSerializer serializer = new JsonSerializer
    {
        ContractResolver = new DefaultContractResolver
        {
            NamingStrategy = new SnakeCaseNamingStrategy()
        }
    };
    
  3. 将JSON解析为JObject

    string json = await response.Content.ReadAsStringAsync();
    JObject root = JObject.Parse(json);
    
  4. 从那里使用LINQ-to-JSON查询来填充Players的列表,如下所示。

    在这里,我将SelectTokens()与递归下降JsonPath表达式一起使用,作为向下钻取player对象的快捷方式。 JSON中的每个播放器实际上是一个包含混合内容数组的数组,其中内容由一些对象(每个对象包含一个不同的属性)和一些无用的空数组组成。因此,我将内部数组过滤为仅包含真实数据的对象,然后使用SelectMany()将其所有属性收集到平面Enumerable<JProperty>中,并将其放置到临时JObject中。从那里,我将ToObject()与先前配置的序列化程序一起使用,以从Player创建一个新的JObject实例并返回Player以便将其放入结果列表。 / p>

    List<Player> players =
        root.SelectTokens("$..player")
            .Select(jt =>
            {
                JObject tempObj = new JObject(
                    jt.Children<JArray>()
                      .First()
                      .Children<JObject>()
                      .SelectMany(jo => jo.Properties())
                );
                return tempObj.ToObject<Player>(serializer);
            })
            .ToList();
    
  5. 如果您想从JSON中获取count并将其与检索到的玩家的实际数量进行比较,则可以这样做:

    int playerCount = (int)root.SelectToken("$..players.count");
    
    if (players.Count != playerCount)
        throw new Exception("The number of players in the list does not match the player count!");
    

这是一个有效的演示:https://dotnetfiddle.net/8KYNNn