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

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

问题描述

我试图序列化/反序列化词典<字符串对象> 这似乎正常工作,如果对象是一个简单的类型,但不工作的时候目的是更复杂的

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; }
}

在我的字典里我添加了一个列表&LT; UrlStatus&GT; 与重定向链和一些简单的字符串的钥匙状态的关键,URL,父代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"}]}

在code我使用序列如下:

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"
  }
]}

当然,我可以再次deserailize这个字符串,我得到正确的对象,但似乎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一个bug。如果你是不是已经在使用最新版本,升级后再试。

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; }
    }


    [Test]
    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(typeof(Dictionary<string, object>), c);

      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应设置为所有

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

文件:<一href=\"http://www.newtonsoft.com/json/help/html/SerializeTypeNameHandling.htm\">TypeNameHandling设置

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

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