从League of Legends API反序列化JSON时出错

时间:2017-11-28 20:40:17

标签: c# json json.net

我正在尝试使用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对象反序列化的数组或List。 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

1 个答案:

答案 0 :(得分:2)

您收到此错误是因为List<Heroes>使用了data,但该属性不是JSON中的数组。您需要使用Dictionary<string, HeroesData>代替。英雄的名字将成为字典的关键。此外,如果要为类中的特定属性使用与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