【发布时间】: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数据“格式错误”。
data是json object而不是array of json objects。您正在尝试将 json 对象反序列化为 json 数组。data由几个属性组成,每个属性都以用户 ID 命名。 IE。Aatrox、Ahri等。您需要为每个属性创建一个新类或使用自定义解析。 -
@SaniSinghHuttunen 我现在明白了。类型、格式和版本对我来说是不必要的,我只需要数据。我怎么得到它?