在升级代码库以使用Json.NET 8.0.1之后,一些反序列化会失败.使用Json.NET 7.0.1一切正常.显然,它是byte[]
导致问题的类型属性的反序列化.如果我删除该byte[]
属性它工作正常.我可以使用这个简单的控制台应用程序重现行为:
internal class Program { private static void Main(string[] args) { Dictionaryaccounts; var jsonSerializerSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple }; using (var streamReader = new StreamReader("accounts.json")) { var json = streamReader.ReadToEnd(); accounts = JsonConvert.DeserializeObject >(json, jsonSerializerSettings); } foreach (var account in accounts) { Debug.WriteLine(account.Value.Name); } } } internal class Account { public string Id { get; set; } public string Name { get; set; } public byte[] EncryptedPassword { get; set; } }
该accounts.json
文件如下所示:
{ "$type": "System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[ConsoleApplication1.Account, ConsoleApplication1]], mscorlib", "lars.michael": { "$type": "ConsoleApplication1.Account, ConsoleApplication1", "EncryptedPassword": { "$type": "System.Byte[], mscorlib", "$value": "cGFzc3dvcmQ=" }, "Name": "Lars Michael", "Id": "lars.michael" }, "john.doe": { "$type": "ConsoleApplication1.Account, ConsoleApplication1", "EncryptedPassword": { "$type": "System.Byte[], mscorlib", "$value": "cGFzc3dvcmQ=" }, "Name": "John Doe", "Id": "john.doe" } }
这可能是Json.NET 8.0.1中的一个错误,还是可以通过调整来解决这个问题JsonSerializerSettings
?
如果有人试图重现这一点,请确保将accounts.json
文件中的程序集名称与控制台应用程序的程序集名称同步(在本例中ConsoleApplication1
).