C# JSON反序列化报错:无法将JSON值转换为Games类
问题原因
你的JSON内容是游戏对象的数组(用[]包裹),但代码里尝试把它反序列化成单个Games类实例,类型不匹配直接导致了JsonException。
修正方案
- 调整反序列化类型:将
JsonSerializer.Deserialize<Games>改为JsonSerializer.Deserialize<List<Games>>,因为JSON是数组结构,对应C#的集合类型。 - 修复类定义语法错误:
public class ReadAndParseJSONFromFile()里的括号是多余的,需要删除。 - 遍历集合打印所有游戏:现在得到的是多个游戏对象,需要循环输出每个对象的信息。
修正后的完整代码
public class Games { public string? Title { get; set;} public int ReleaseYear { get; set;} public double Rating { get; set;} } public class ReadAndParseJSONFromFile { public static void ReadingJSON() { string filePath = @"C:\Users\Kodain\C#\Game Data Parser\games.json"; string jsonString = File.ReadAllText(filePath); List<Games> gamesList = JsonSerializer.Deserialize<List<Games>>(jsonString)!; System.Console.WriteLine("Loaded games are: "); foreach (var game in gamesList) { System.Console.WriteLine($"{game.Title}, released in {game.ReleaseYear}, rating: {game.Rating}"); } } }
补充提示
- 不确定JSON结构对应的C#类型时,可以用Visual Studio的「编辑→选择性粘贴→将JSON粘贴为类」功能自动生成匹配的结构,减少手动定义的错误。
- 空值处理:代码里的
!是null包容运算符,如果JSON可能为空,建议添加空值检查(比如if(gamesList == null) return;),避免触发空引用异常。
内容的提问来源于stack exchange,提问作者C L
相关产品推荐
相关产品推荐

