C#使用Newtonsoft.Json反序列化JSON为Game列表报字符串转集合错误
问题根因与修复方案
核心错误:重复序列化JSON字符串
你的写入逻辑存在二次序列化问题:
backUp_Games方法中已经将List<Game>对象序列化为合法的JSON数组字符串jsonGames- 调用
backUp方法写入文件时,你又对已经是JSON格式的字符串执行了一次JsonConvert.SerializeObject,导致最终写入文件的内容是被转义的JSON字符串,而非原始JSON数组。比如文件实际内容开头会多一个双引号,所有内部引号都被加上了\转义符,反序列化时解析器读到的是一个完整字符串,自然无法转换为List<Game>类型。
修复代码:
public void backUp(string fileName ,string json) { string filename = @"C:\.....\Desktop\JsonTest\"+fileName+".json"; // 直接写入传入的已序列化JSON,不要二次序列化 File.WriteAllText(filename, json); }
次要问题:Game类不满足反序列化要求
反序列化时Newtonsoft.Json需要能够构造对象并给属性赋值,你的Game类存在两个适配问题:
ID属性只有get访问器,反序列化时无法给ID属性赋值- 没有无参构造函数,反序列化时无法构造Game类实例
修复后的Game类:
public class Game : AbstGame { [JsonProperty("ID")] // 新增set访问器 public override int ID { get; set; } [JsonProperty("Title")] public override string Title { get ; set ; } [JsonProperty("MinAge")] public override int MinAge { get ; set ; } [JsonProperty("Price")] public override double Price { get; set ; } [JsonProperty("State")] public override string State { get; set ; } [JsonProperty("Players")] public int Players { get; set; } // 新增无参构造函数,供反序列化调用 public Game() { } public Game(string title, int minAge, double price,string state, int players) { Random rnd = new Random(); ID = rnd.Next(1, 999999999); Title = title; MinAge = minAge; Price = price; State = state; Players = players; } }
可选优化:简化反序列化代码
你可以直接用JsonConvert.DeserializeObject方法简化加载逻辑,无需手动构造JsonReader:
public List<Game> loadData_Games() { List<Game> Gl = new List<Game>(); string[] files = Directory.GetFiles(folder, "games.json"); foreach (string file in files) { string json = File.ReadAllText(file); Gl = JsonConvert.DeserializeObject<List<Game>>(json); } return Gl; }
内容的提问来源于stack exchange,提问作者TreeGardner
相关产品推荐
相关产品推荐

