使用JSON.NET序列化反序列化对象字典

使用JSON.NET序列化反序列化对象字典,第1张

使用JSON.NET序列化/反序列化对象字典

我认为这是旧版Json.NET中的错误。如果您尚未使用最新版本,请升级并重试。

    public class UrlStatus    {      public int Status { get; set; }      public string Url { get; set; }    }    [TestMethod]    public void GenericDictionaryObject()    {      Dictionary<string, object> collection = new Dictionary<string, object>()        {          {"First", new UrlStatus{ Status = 404, Url = @"http://www.bing.com"}},          {"Second", new UrlStatus{Status = 400, Url = @"http://www.google.com"}},          {"List", new List<UrlStatus> {   new UrlStatus {Status = 300, Url = @"http://www.yahoo.com"},   new UrlStatus {Status = 200, Url = @"http://www.askjeeves.com"} }          }        };      string json = JsonConvert.SerializeObject(collection, Formatting.Indented, new JsonSerializerSettings      {        TypeNameHandling = TypeNameHandling.All,        TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple      });      Assert.AreEqual(@"{  ""$type"": ""System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib"",  ""First"": {    ""$type"": ""Newtonsoft.Json.Tests.Serialization.TypeNameHandlingTests+UrlStatus, Newtonsoft.Json.Tests"",    ""Status"": 404,    ""Url"": ""http://www.bing.com""  },  ""Second"": {    ""$type"": ""Newtonsoft.Json.Tests.Serialization.TypeNameHandlingTests+UrlStatus, Newtonsoft.Json.Tests"",    ""Status"": 400,    ""Url"": ""http://www.google.com""  },  ""List"": {    ""$type"": ""System.Collections.Generic.List`1[[Newtonsoft.Json.Tests.Serialization.TypeNameHandlingTests+UrlStatus, Newtonsoft.Json.Tests]], mscorlib"",    ""$values"": [      {        ""$type"": ""Newtonsoft.Json.Tests.Serialization.TypeNameHandlingTests+UrlStatus, Newtonsoft.Json.Tests"",        ""Status"": 300,        ""Url"": ""http://www.yahoo.com""      },      {        ""$type"": ""Newtonsoft.Json.Tests.Serialization.TypeNameHandlingTests+UrlStatus, Newtonsoft.Json.Tests"",        ""Status"": 200,        ""Url"": ""http://www.askjeeves.com""      }    ]  }}", json);      object c = JsonConvert.DeserializeObject(json, new JsonSerializerSettings      {        TypeNameHandling = TypeNameHandling.All,        TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple      });      Assert.IsInstanceOfType(c, typeof(Dictionary<string, object>));      Dictionary<string, object> newCollection = (Dictionary<string, object>)c;      Assert.AreEqual(3, newCollection.Count);      Assert.AreEqual(@"http://www.bing.com", ((UrlStatus)newCollection["First"]).Url);      List<UrlStatus> statues = (List<UrlStatus>) newCollection["List"];      Assert.AreEqual(2, statues.Count);    }  }

编辑,我刚刚注意到您提到了一个列表。TypeNameHandling应该设置为All。

文档:
TypeNameHandling设置



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5089823.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-16
下一篇2022-11-16

发表评论

登录后才能评论

评论列表(0条)

    保存