使用 Newtonsoft.Json 从 Steam 商店 API 获取数据

Getting data from Steam Store API using Newtonsoft.Json

我正在尝试从 Steam 商店获取数据 API。目标是向它传递一个 AppID,然后使用 API 获取该游戏的数据并将其存储在 Game 对象中。我正在获取数据直到序列化。下面是我使用的代码:

namespace GData
{

    public class Rootobject
    {
        public Game _9050 { get; set; }
    }

    public class Game
    {
        public bool success { get; set; }
        public Data data { get; set; }
    }

    public class Data
    {
        public string type { get; set; }
        public string name { get; set; }
        public int steam_appid { get; set; }
        public int required_age { get; set; }
        public bool is_free { get; set; }
        public string detailed_description { get; set; }
        public string about_the_game { get; set; }
        public string short_description { get; set; }
        public string supported_languages { get; set; }
        public string header_image { get; set; }
        public string website { get; set; }
        public Pc_Requirements pc_requirements { get; set; }
        public object[] mac_requirements { get; set; }
        public object[] linux_requirements { get; set; }
        public string[] developers { get; set; }
        public string[] publishers { get; set; }
        public Price_Overview price_overview { get; set; }
        public int[] packages { get; set; }
        public Package_Groups[] package_groups { get; set; }
        public Platforms platforms { get; set; }
        public Metacritic metacritic { get; set; }
        public Category[] categories { get; set; }
        public Genre[] genres { get; set; }
        public Screenshot[] screenshots { get; set; }
        public Recommendations recommendations { get; set; }
        public Release_Date release_date { get; set; }
        public Support_Info support_info { get; set; }
        public string background { get; set; }
    }

    public class Pc_Requirements
    {
        public string minimum { get; set; }
    }

    public class Price_Overview
    {
        public string currency { get; set; }
        public int initial { get; set; }
        public int final { get; set; }
        public int discount_percent { get; set; }
    }

    public class Platforms
    {
        public bool windows { get; set; }
        public bool mac { get; set; }
        public bool linux { get; set; }
    }

    public class Metacritic
    {
        public int score { get; set; }
        public string url { get; set; }
    }

    public class Recommendations
    {
        public int total { get; set; }
    }

    public class Release_Date
    {
        public bool coming_soon { get; set; }
        public string date { get; set; }
    }

    public class Support_Info
    {
        public string url { get; set; }
        public string email { get; set; }
    }

    public class Package_Groups
    {
        public string name { get; set; }
        public string title { get; set; }
        public string description { get; set; }
        public string selection_text { get; set; }
        public string save_text { get; set; }
        public int display_type { get; set; }
        public string is_recurring_subscription { get; set; }
        public Sub[] subs { get; set; }
    }

    public class Sub
    {
        public int packageid { get; set; }
        public string percent_savings_text { get; set; }
        public int percent_savings { get; set; }
        public string option_text { get; set; }
        public string option_description { get; set; }
        public string can_get_free_license { get; set; }
        public bool is_free_license { get; set; }
        public int price_in_cents_with_discount { get; set; }
    }

    public class Category
    {
        public int id { get; set; }
        public string description { get; set; }
    }

    public class Genre
    {
        public string id { get; set; }
        public string description { get; set; }
    }

    public class Screenshot
    {
        public int id { get; set; }
        public string path_thumbnail { get; set; }
        public string path_full { get; set; }
    }

}

正在获取 JSON:

 public class GameData
    {
        public Game GetGameData(int GameId)
        {
            var url = "https://store.steampowered.com/api/appdetails/?appids=" + GameId.ToString();
            //Game GameData = _download_serialized_json_data<Game>(url);
            HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format(url));

            WebReq.Method = "GET";

            HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();

            Console.WriteLine(WebResp.StatusCode);
            Console.WriteLine(WebResp.Server);

            string jsonString;
            using (Stream stream = WebResp.GetResponseStream())  
            {
                StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
                jsonString = reader.ReadToEnd();
            }

            Game GameData = new Game();

            GameData = JsonConvert.DeserializeObject<Game>(jsonString);

            return GameData;
        }

    }

代码是 returning success: false。

问题似乎出在反序列化中,因为 jsonString = reader.ReadToEnd(); jsonString 变量中的数据已满。

Gameclass有什么问题吗?

我正在使用 C# 和 Newtonsoft JSON 库。

jsonString (https://store.steampowered.com/api/appdetails/?appids=570) 中检索到的示例 JSON:

 {
   "570":{
      "success":true,
      "data":{
         "type":"game",
         "name":"Dota 2",
         "steam_appid":570,
         "required_age":0,
         "is_free":true,
         "dlc":[
            859040
         ],
         "detailed_description":"<strong>The most-played game on Steam.<\/strong><br>Every day, millions of players worldwide enter battle as one of over a hundred Dota heroes. And no matter if it's their 10th hour of play or 1,000th, there's always something new to discover. With regular updates that ensure a constant evolution of gameplay, features, and heroes, Dota 2 has truly taken on a life of its own.<br><br><strong>One Battlefield. Infinite Possibilities.<\/strong><br>When it comes to diversity of heroes, abilities, and powerful items, Dota boasts an endless array\u2014no two games are the same. Any hero can fill multiple roles, and there's an abundance of items to help meet the needs of each game. Dota doesn't provide limitations on how to play, it empowers you to express your own style.<br><br><strong>All heroes are free.<\/strong><br>Competitive balance is Dota's crown jewel, and to ensure everyone is playing on an even field, the core content of the game\u2014like the vast pool of heroes\u2014is available to all players. Fans can collect cosmetics for heroes and fun add-ons for the world they inhabit, but everything you need to play is already included before you join your first match.<br><br><strong>Bring your friends and party up.<\/strong><br>Dota is deep, and constantly evolving, but it's never too late to join. <br>Learn the ropes playing co-op vs. bots. Sharpen your skills in the hero demo mode. Jump into the behavior- and skill-based matchmaking system that ensures you'll <br>be matched with the right players each game.",
         "about_the_game":"<strong>The most-played game on Steam.<\/strong><br>Every day, millions of players worldwide enter battle as one of over a hundred Dota heroes. And no matter if it's their 10th hour of play or 1,000th, there's always something new to discover. With regular updates that ensure a constant evolution of gameplay, features, and heroes, Dota 2 has truly taken on a life of its own.<br><br><strong>One Battlefield. Infinite Possibilities.<\/strong><br>When it comes to diversity of heroes, abilities, and powerful items, Dota boasts an endless array\u2014no two games are the same. Any hero can fill multiple roles, and there's an abundance of items to help meet the needs of each game. Dota doesn't provide limitations on how to play, it empowers you to express your own style.<br><br><strong>All heroes are free.<\/strong><br>Competitive balance is Dota's crown jewel, and to ensure everyone is playing on an even field, the core content of the game\u2014like the vast pool of heroes\u2014is available to all players. Fans can collect cosmetics for heroes and fun add-ons for the world they inhabit, but everything you need to play is already included before you join your first match.<br><br><strong>Bring your friends and party up.<\/strong><br>Dota is deep, and constantly evolving, but it's never too late to join. <br>Learn the ropes playing co-op vs. bots. Sharpen your skills in the hero demo mode. Jump into the behavior- and skill-based matchmaking system that ensures you'll <br>be matched with the right players each game.",
         "short_description":"Every day, millions of players worldwide enter battle as one of over a hundred Dota heroes. And no matter if it's their 10th hour of play or 1,000th, there's always something new to discover. With regular updates that ensure a constant evolution of gameplay, features, and heroes, Dota 2 has truly taken on a life of its own.",
         "supported_languages":"Bulgarian, Czech, Danish, Dutch, English<strong>*<\/strong>, Finnish, French, German, Greek, Hungarian, Italian, Japanese, Korean<strong>*<\/strong>, Norwegian, Polish, Portuguese, Portuguese-Brazil, Romanian, Russian, Simplified Chinese<strong>*<\/strong>, Spanish, Swedish, Thai, Traditional Chinese, Turkish, Ukrainian<br><strong>*<\/strong>languages with full audio support",
         "reviews":"\u201cA modern multiplayer masterpiece.\u201d<br>9.5\/10 \u2013 <a href=\"https:\/\/www.destructoid.com\/review-dota-2-258506.phtml\" target=\"_blank\" rel=\"noreferrer\"  >Destructoid<\/a><br><br>\u201cOnce you start to learn its secrets, there\u2019s a wild and exciting variety of play here that\u2019s unmatched, even by its peers.\u201d<br>9.4\/10 \u2013 <a href=\"http:\/\/www.ign.com\/articles\/2013\/07\/24\/dota-2-review\" target=\"_blank\" rel=\"noreferrer\"  >IGN<\/a><br><br>\u201cDota 2 is possibly the only competitive free-to-play game that is totally uncompromised by its business model.\u201d<br>90\/100 \u2013 <a href=\"http:\/\/www.pcgamer.com\/dota-2-review-2\/\" target=\"_blank\" rel=\"noreferrer\"  >PC Gamer<\/a><br>",
         "header_image":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/570\/header.jpg?t=1525818062",
         "website":"http:\/\/www.dota2.com\/",
         "pc_requirements":{
            "minimum":"<strong>Minimum:<\/strong><br><ul class=\"bb_ul\"><li><strong>OS:<\/strong> Windows 7 or newer<br><\/li><li><strong>Processor:<\/strong> Dual core from Intel or AMD at 2.8 GHz<br><\/li><li><strong>Memory:<\/strong> 4 GB RAM<br><\/li><li><strong>Graphics:<\/strong> nVidia GeForce 8600\/9600GT, ATI\/AMD Radeon HD2600\/3600<br><\/li><li><strong>DirectX:<\/strong> Version 9.0c<br><\/li><li><strong>Network:<\/strong> Broadband Internet connection<br><\/li><li><strong>Storage:<\/strong> 15 GB available space<br><\/li><li><strong>Sound Card:<\/strong> DirectX Compatible<\/li><\/ul>"
         },
         "mac_requirements":{
            "minimum":"<strong>Minimum:<\/strong><br><ul class=\"bb_ul\"><li><strong>OS:<\/strong> OS X Mavericks 10.9 or newer<br><\/li><li><strong>Processor:<\/strong> Dual core from Intel<br><\/li><li><strong>Memory:<\/strong> 4 GB RAM<br><\/li><li><strong>Graphics:<\/strong> nVidia 320M or higher, or Radeon HD 2400 or higher, or Intel HD 3000 or higher<br><\/li><li><strong>Network:<\/strong> Broadband Internet connection<br><\/li><li><strong>Storage:<\/strong> 15 GB available space<\/li><\/ul>"
         },
         "linux_requirements":{
            "minimum":"<strong>Minimum:<\/strong><br><ul class=\"bb_ul\"><li><strong>OS:<\/strong> Ubuntu 12.04 or newer<br><\/li><li><strong>Processor:<\/strong> Dual core from Intel or AMD at 2.8 GHz<br><\/li><li><strong>Memory:<\/strong> 4 GB RAM<br><\/li><li><strong>Graphics:<\/strong> nVidia Geforce 8600\/9600GT (Driver v331), AMD HD 2xxx-4xxx (Driver mesa 10.5.9), AMD HD 5xxx+ (Driver mesa 10.5.9 or Catalyst 15.7), Intel HD 3000 (Driver mesa 10.6)<br><\/li><li><strong>Network:<\/strong> Broadband Internet connection<br><\/li><li><strong>Storage:<\/strong> 15 GB available space<br><\/li><li><strong>Sound Card:<\/strong> OpenAL Compatible Sound Card<\/li><\/ul>"
         },
         "developers":[
            "Valve"
         ],
         "publishers":[
            "Valve"
         ],
         "packages":[
            197846
         ],
         "package_groups":[
            {
               "name":"default",
               "title":"Buy Dota 2",
               "description":"",
               "selection_text":"Select a purchase option",
               "save_text":"",
               "display_type":0,
               "is_recurring_subscription":"false",
               "subs":[
                  {
                     "packageid":197846,
                     "percent_savings_text":"",
                     "percent_savings":0,
                     "option_text":"Dota 2 - Commercial License - Free",
                     "option_description":"",
                     "can_get_free_license":"0",
                     "is_free_license":true,
                     "price_in_cents_with_discount":0
                  }
               ]
            }
         ],
         "platforms":{
            "windows":true,
            "mac":true,
            "linux":true
         },
         "metacritic":{
            "score":90,
            "url":"http:\/\/www.metacritic.com\/game\/pc\/dota-2?ftag=MCD-06-10aaa1f"
         },
         "categories":[
            {
               "id":1,
               "description":"Multi-player"
            },
            {
               "id":9,
               "description":"Co-op"
            },
            {
               "id":29,
               "description":"Steam Trading Cards"
            },
            {
               "id":30,
               "description":"Steam Workshop"
            },
            {
               "id":40,
               "description":"SteamVR Collectibles"
            },
            {
               "id":35,
               "description":"In-App Purchases"
            },
            {
               "id":8,
               "description":"Valve Anti-Cheat enabled"
            }
         ],
         "genres":[
            {
               "id":"1",
               "description":"Action"
            },
            {
               "id":"37",
               "description":"Free to Play"
            },
            {
               "id":"2",
               "description":"Strategy"
            }
         ],
         "screenshots":[
            {
               "id":0,
               "path_thumbnail":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/570\/ss_86d675fdc73ba10462abb8f5ece7791c5047072c.600x338.jpg?t=1525818062",
               "path_full":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/570\/ss_86d675fdc73ba10462abb8f5ece7791c5047072c.1920x1080.jpg?t=1525818062"
            },
            {
               "id":1,
               "path_thumbnail":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/570\/ss_ad8eee787704745ccdecdfde3a5cd2733704898d.600x338.jpg?t=1525818062",
               "path_full":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/570\/ss_ad8eee787704745ccdecdfde3a5cd2733704898d.1920x1080.jpg?t=1525818062"
            },
            {
               "id":2,
               "path_thumbnail":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/570\/ss_7ab506679d42bfc0c0e40639887176494e0466d9.600x338.jpg?t=1525818062",
               "path_full":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/570\/ss_7ab506679d42bfc0c0e40639887176494e0466d9.1920x1080.jpg?t=1525818062"
            },
            {
               "id":3,
               "path_thumbnail":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/570\/ss_c9118375a2400278590f29a3537769c986ef6e39.600x338.jpg?t=1525818062",
               "path_full":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/570\/ss_c9118375a2400278590f29a3537769c986ef6e39.1920x1080.jpg?t=1525818062"
            },
            {
               "id":4,
               "path_thumbnail":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/570\/ss_f9ebafedaf2d5cfb80ef1f74baa18eb08cad6494.600x338.jpg?t=1525818062",
               "path_full":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/570\/ss_f9ebafedaf2d5cfb80ef1f74baa18eb08cad6494.1920x1080.jpg?t=1525818062"
            },
            {
               "id":5,
               "path_thumbnail":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/570\/ss_27b6345f22243bd6b885cc64c5cda74e4bd9c3e8.600x338.jpg?t=1525818062",
               "path_full":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/570\/ss_27b6345f22243bd6b885cc64c5cda74e4bd9c3e8.1920x1080.jpg?t=1525818062"
            },
            {
               "id":6,
               "path_thumbnail":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/570\/ss_b33a65678dc71cc98df4890e22a89601ee56a918.600x338.jpg?t=1525818062",
               "path_full":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/570\/ss_b33a65678dc71cc98df4890e22a89601ee56a918.1920x1080.jpg?t=1525818062"
            },
            {
               "id":7,
               "path_thumbnail":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/570\/ss_d0f973ce376ca5b6c08e081cb035e86ced105fa9.600x338.jpg?t=1525818062",
               "path_full":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/570\/ss_d0f973ce376ca5b6c08e081cb035e86ced105fa9.1920x1080.jpg?t=1525818062"
            },
            {
               "id":8,
               "path_thumbnail":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/570\/ss_1f3b5f5ccf8b159294914c3fe028128a787304b6.600x338.jpg?t=1525818062",
               "path_full":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/570\/ss_1f3b5f5ccf8b159294914c3fe028128a787304b6.1920x1080.jpg?t=1525818062"
            },
            {
               "id":9,
               "path_thumbnail":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/570\/ss_e0a92f15a6631a8186df79182d0fe28b5e37d8cb.600x338.jpg?t=1525818062",
               "path_full":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/570\/ss_e0a92f15a6631a8186df79182d0fe28b5e37d8cb.1920x1080.jpg?t=1525818062"
            }
         ],
         "movies":[
            {
               "id":256692021,
               "name":"Dota 2 - Join the Battle",
               "thumbnail":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/256692021\/movie.293x165.jpg?t=1501892790",
               "webm":{
                  "480":"http:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/256692021\/movie480.webm?t=1501892790",
                  "max":"http:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/256692021\/movie_max.webm?t=1501892790"
               },
               "highlight":true
            },
            {
               "id":256692017,
               "name":"Dota 2 - Sizzle Reel",
               "thumbnail":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/256692017\/movie.293x165.jpg?t=1501892798",
               "webm":{
                  "480":"http:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/256692017\/movie480.webm?t=1501892798",
                  "max":"http:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/256692017\/movie_max.webm?t=1501892798"
               },
               "highlight":true
            },
            {
               "id":2028243,
               "name":"Dota 2 - The Greeviling",
               "thumbnail":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/2028243\/movie.293x165.jpg?t=1447357208",
               "webm":{
                  "480":"http:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/2028243\/movie480.webm?t=1447357208",
                  "max":"http:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/2028243\/movie_max.webm?t=1447357208"
               },
               "highlight":false
            },
            {
               "id":81026,
               "name":"Dota 2 Gamescom Trailer",
               "thumbnail":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/81026\/movie.293x165.jpg?t=1501892804",
               "webm":{
                  "480":"http:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/81026\/movie480.webm?t=1501892804",
                  "max":"http:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/81026\/movie_max.webm?t=1501892804"
               },
               "highlight":false
            },
            {
               "id":2040250,
               "name":"Dota 2 Reborn - Custom Games Are Here",
               "thumbnail":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/2040250\/movie.293x165.jpg?t=1447376742",
               "webm":{
                  "480":"http:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/2040250\/movie480.webm?t=1447376742",
                  "max":"http:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/2040250\/movie_max.webm?t=1447376742"
               },
               "highlight":false
            }
         ],
         "recommendations":{
            "total":911325
         },
         "release_date":{
            "coming_soon":false,
            "date":"9 Jul, 2013"
         },
         "support_info":{
            "url":"http:\/\/dev.dota2.com\/",
            "email":""
         },
         "background":"https:\/\/steamcdn-a.akamaihd.net\/steam\/apps\/570\/page_bg_generated_v6b.jpg?t=1525818062"
      }
   }
}

更新:如果我 return 数据数据类型所有值都为 null

    public Data GetGameData(int GameId)
    {
    var url = "https://store.steampowered.com/api/appdetails/?appids=" + GameId.ToString();
    //Game GameData = _download_serialized_json_data<Game>(url);
    HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format(url));

    WebReq.Method = "GET";

    HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();

    Console.WriteLine(WebResp.StatusCode);
    Console.WriteLine(WebResp.Server);

    string jsonString;
    using (Stream stream = WebResp.GetResponseStream())
    {
        StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
        jsonString = reader.ReadToEnd();
    }

    var dict = JsonConvert.DeserializeObject<Dictionary<string, Data>>(jsonString);

    Data gameData = dict[GameId.ToString()];

    return gameData;
}

如果我 return 游戏数据类型我得到同样的错误:

 public Game GetGameData(int GameId)
            {
            var url = "https://store.steampowered.com/api/appdetails/?appids=" + GameId.ToString();
            //Game GameData = _download_serialized_json_data<Game>(url);
            HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format(url));

            WebReq.Method = "GET";

            HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();

            Console.WriteLine(WebResp.StatusCode);
            Console.WriteLine(WebResp.Server);

            string jsonString;
            using (Stream stream = WebResp.GetResponseStream())
            {
                StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
                jsonString = reader.ReadToEnd();
            }

            var dict = JsonConvert.DeserializeObject<Dictionary<string, Game>>(jsonString);

            Game gameData = dict[GameId.ToString()];

            return gameData;
        }

在您的代码中,您试图反序列化为包含 successdata 属性的 Game class。但是,在示例 JSON 中,这些属性不在根级别。相反,它们在更下一层,在一个名为 570 的 属性 中,我猜它是游戏 ID:

{
  "570": {
    "success": true,
    "data": {
      ...
    }
  }
}

由于您要反序列化的 class 与 JSON 不匹配,您得到的是默认值(即 success 是 false 而 data 是空)。

要解决这个问题,您需要一些东西来包装您的 Game class。由于游戏 ID 可能会根据请求而改变,因此您不能使用 Rootobject 之类的常规 class。相反,您需要像这样反序列化为 Dictionary<string, Game>

var dict = JsonConvert.DeserializeObject<Dictionary<string, Game>>(jsonString);

然后您可以从中检索 Game 对象:

Game gameData = dict[GameId.ToString()];

这是一个工作演示:https://dotnetfiddle.net/ieT839

注意:在您的 classes 中,您可以省略您并不真正需要的成员。在玩不同的游戏 ID 时,我发现 JSON 中的 pc_requirementsmac_requirementslinux_requirements 元素有时可以是一个对象,有时是一个对象数组。如果你有你的 classes 声明期望一件事而 JSON returns 另一件事,那么你将在反序列化时得到一个错误。您可以使用自定义 JsonConverter like the SingleOrArrayConverter<T> from How to handle both a single item and an array for the same property using JSON.net 解决此问题。但是如果你真的不需要这些项目,你可以通过在 Data class.

中将它们注释掉来回避这个问题。