【问题标题】:Error when deserializing JSON from League of Legends API从英雄联盟 API 反序列化 JSON 时出错
【发布时间】:2017-11-28 20:40:16
【问题描述】:

我正在尝试使用 RiotGames Api。我有 JSON 数据,需要将此 JSON 反序列化为 c# 类,但出现错误:

Newtonsoft.Json.JsonSerializationException: '无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List`1[WFALeagueOfLegendsAPI.Heroes]' 因为该类型需要正确反序列化的 JSON 数组(例如 [1,2,3])。 要修复此错误,要么将 JSON 更改为 JSON 数组(例如 [1,2,3]),要么将反序列化类型更改为普通的 .NET 类型(例如,不是像整数这样的原始类型,而不是像这样的集合类型可以从 JSON 对象反序列化的数组或列表。 JsonObjectAttribute 也可以添加到类型中以强制它从 JSON 对象反序列化。 路径“datas.Aatrox”,第 1 行,位置 85。

我的课程:

    public class JsonRoot
    {
        public string type { get; set; }
        public string format { get; set; }
        public string version { get; set; }
        public List<Heroes> datas { get; set; }
    }

    public class Heroes
    {
        public HeroesData Name { get; set; }
    }

    public class HeroesData
    {
        public string version { get; set; }
        public string id { get; set; }
        public string key { get; set; }
        public string name { get; set; }
        public string title { get; set; }
        public HeroImage image { get; set; }
    }

    public class HeroImage
    {
        public string full { get; set; }
        public string sprite { get; set; }
        public string group { get; set; }

        public override string ToString()
        {
            return full;
        }
    }

C#代码:

var json = new WebClient().DownloadString("http://ddragon.leagueoflegends.com/cdn/6.24.1/data/en_US/champion.json");

json = json.Replace("data", "datas");
JsonRoot jr = JsonConvert.DeserializeObject<JsonRoot>(json); // this line has the error

【问题讨论】:

  • 通常 Newtsoft 可以很好地处理数组列表,但是,作为一个简单的 hack,只需将英雄列表更改为数组
  • 该属性被命名为data 而不是datas。重命名属性或使用JsonPropertyAttribute:[JsonProperty(PropertyName="data")]。切勿使用Replace 重新格式化数据。
  • @SaniSinghHuttunen 我试试你的建议,但同样的错误。如果我使用替换来修复数据错误但返回 null :/
  • 问题是json数据“格式错误”。 datajson object 而不是 array of json objects。您正在尝试将 json 对象反序列化为 json 数组。 data 由几个属性组成,每个属性都以用户 ID 命名。 IE。 AatroxAhri 等。您需要为每个属性创建一个新类或使用自定义解析。
  • @SaniSinghHuttunen 我现在明白了。类型、格式和版本对我来说是不必要的,我只需要数据。我怎么得到它?

标签: c# json json.net


【解决方案1】:

您收到此错误是因为您将 List&lt;Heroes&gt; 用于 data,但该属性不是 JSON 中的数组。您需要改用Dictionary&lt;string, HeroesData&gt;。英雄的名字将是字典的键。此外,如果您想为类中的特定属性使用与 JSON 中不同的名称,您可以使用 [JsonProperty] 属性,如下所示。使用 string.Replace 尝试更改 JSON 以适应您的课程并不是一个好主意,因为您最终可能会替换您不想要的东西。

public class JsonRoot
{
    public string type { get; set; }
    public string format { get; set; }
    public string version { get; set; }
    [JsonProperty("data")]
    public Dictionary<string, HeroesData> heroes { get; set; }
}

小提琴:https://dotnetfiddle.net/kuKSrk

【讨论】:

    猜你喜欢
    • 2020-12-21
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多