使用 JSON.NET 序列化/反序列化对象字典 [英] Serializing/Deserializing Dictionary of objects with JSON.NET

查看:36
本文介绍了使用 JSON.NET 序列化/反序列化对象字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试序列化/反序列化一个 Dictionary<string, object>,如果对象是简单类型,这似乎可以正常工作,但当对象更复杂时就无法正常工作.

I'm trying to serialize/deserialize a Dictionary<string, object> which seems to work fine if the object is a simple type but doesn't work when the object is more complex.

我有这门课:

public class UrlStatus
{
 public int Status { get; set; }
 public string Url { get; set; }
}

在我的字典中,我添加了一个 List<UrlStatus> 键为重定向链"和一些简单的字符串,键为Status"、Url"、Parent Url".我从 JSON.Net 返回的字符串如下所示:

In my dictionary I add a List<UrlStatus> with a key of "Redirect Chain" and a few simple strings with keys "Status", "Url", "Parent Url". The string I'm getting back from JSON.Net looks like this:

{"$type":"System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib","Status":"OK","Url":"http://www.ehow.com/m/how_5615409_create-pdfs-using-bean.html","Parent Url":"http://www.ehow.com/mobilearticle35.xml","Redirect Chain":[{"$type":"Demand.TestFramework.Core.Entities.UrlStatus, Demand.TestFramework.Core","Status":301,"Url":"http://www.ehow.com/how_5615409_create-pdfs-using-bean.html"}]}

我用来序列化的代码如下:

The code I'm using to serialize looks like:

JsonConvert.SerializeObject(collection, Formatting.None, new JsonSerializerSettings 
{ 
 TypeNameHandling = TypeNameHandling.Objects, 
 TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple 
});

反序列化我正在做的事情:

to deserialize I'm doing:

JsonConvert.DeserializeObject<T>(collection, new JsonSerializerSettings
{
 TypeNameHandling = TypeNameHandling.Objects,
 TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple, 
});

字典恢复正常,所有字符串恢复正常,但列表没有正确反序列化.它只是回来了

The Dictionary comes back fine, all the strings come back fine, but the List doesn't get properly deserialized. It just comes back as

{[
  {
    "$type": "XYZ.TestFramework.Core.Entities.UrlStatus, XYZ.TestFramework.Core",
    "Status": 301,
    "Url": "/how_5615409_create-pdfs-using-bean.html"
  }
]}

当然,我可以再次使该字符串脱轨并得到正确的对象,但似乎 JSON.Net 应该为我完成此操作.显然我做错了什么,但我不知道是什么.

Of course I can deserailize this string again and I get the correct object, but it seems like JSON.Net should have done this for me. Clearly I'm doing something wrong, but I don't know what it is.

推荐答案

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

I think that is a bug in an older version of Json.NET. If you aren't already using the latest version, upgrade and try again.

    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.

Edit, I just noticed you mentioned a list. TypeNameHandling should be set to All.

文档:TypeNameHandling 设置

这篇关于使用 JSON.NET 序列化/反序列化对象字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆