首页 > 解决方案 > 在 .NET 中反序列化 Pokemon API

问题描述

我正在尝试反序列化位于https://pokeapi.co/api/v2/pokemon/3的 pokemon API,而且我对使用 json 比较陌生。我已经创建了一个类和方法,可以将我选择的任何 pokemon 加载到一个对象中,但只能让它使用简单的键,如“name: value”和“id: value”


 class Pokemon
    {
        [JsonProperty("id")]
        public int Id { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

      //  [JsonProperty("abilities")]
      //  public Dictionary<string, string>[] Abilities { get; set; }

        //[JsonProperty("types")]
        // public Dictionary<string, int>[] Types { get; set; }

        //[JsonProperty("sprites")]
        //public Dictionary<string, string> Sprites { get; set; }

        public static Pokemon LoadPokemon(int num)
        {  
            string json = new WebClient().DownloadString($"https://pokeapi.co/api/v2/pokemon/{num}");
            Pokemon pokemon = JsonConvert.DeserializeObject<Pokemon>(json);
            return pokemon;
        }
    }

我已经注释掉的所有我无法工作的领域。基本上我的问题是如何使我注释掉的那些字段实际加载。我尝试过将字典、数组和列表组合为数据类型,但我似乎无法使任何工作。

 "sprites": {
    "back_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/3.png",
    "back_female": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/female/3.png",
    "back_shiny": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/shiny/3.png",
    "back_shiny_female": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/shiny/female/3.png",
    "front_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/3.png",
    "front_female": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/female/3.png",
    "front_shiny": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/3.png",
    "front_shiny_female": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/female/3.png",
    "other": {
      "dream_world": {
        "front_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/dream-world/3.svg",
        "front_female": null
      },
      "official-artwork": {
        "front_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/3.png"
      }
    },

'解析值时遇到意外字符:{. 路径“sprites.other”,第 1 行,位置 189387。这是我尝试加载精灵时的常见错误消息,其他属性也有类似的错误。我可以看到为什么“其他:”键不能与 Dict<string, string> 一起使用,但我也不知道如何避免这个问题,因为不是精灵中的每个键都具有这种格式。

我也在使用 NewtonSoft.Json 和 System.Net 包。您可以在https://pokeapi.co/找到 API 的缩写版本。

标签: c#jsonrestjson.netdeserialization

解决方案


尝试为非常复杂的 JSON 文档找出正确的 C# 结构可能非常困难。我建议您首先使用众多在线 JSON 到 C# 转换器工具之一(例如https://app.quicktype.io/或 Google“JSON 到 C#”)来获取示例 JSON 文档并生成您的类模型。使用来自https://pokeapi.co/的示例 JSON ,我使用 quicktype 工具立即生成 C# 模型。然后,您可以获取该 C# 代码并对其进行修改以满足您的需要(为每个类创建单独的文件、删除不需要的属性等)。但至少这为您提供了一个好的(有效的)起点。诸如 quicktype 之类的工具具有配置选项,可让您优化模型,例如,如果您希望 JSON 数组成为 C# 数组或列表等。


推荐阅读