无法使用Json.net使用Complex键序列化Dictionary

我有一个自定义.net类型的字典作为其密钥。我正在尝试使用JSON.net将此字典序列化为JSON,但是它无法在序列化期间将密钥转换为适当的值。

class ListBaseClass { public String testA; public String testB; } ----- var details = new Dictionary(); details.Add(new ListBaseClass { testA = "Hello", testB = "World" }, "Normal"); var results = Newtonsoft.Json.JsonConvert.SerializeObject(details); var data = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary> results); 

这个给我 – >“{\”JSonSerialization.ListBaseClass \“:\”Normal \“}”

但是,如果我将自定义类型作为字典中的值,它可以很好地工作

  var details = new Dictionary(); details.Add("Normal", new ListBaseClass { testA = "Hello", testB = "World" }); var results = Newtonsoft.Json.JsonConvert.SerializeObject(details); var data = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary>(results); 

这个给我 – >“{\”普通\“:{\”testA \“:\”Hello \“,\”testB \“:\”World \“}}”

有人建议如果我遇到Json.net的某些限制或我做错了什么?

序列化指南说明(参见章节:字典和Hashtables;感谢@Shashwat的链接):

序列化字典时,字典的键将转换为字符串并用作JSON对象属性名称。 为密钥编写的字符串可以通过覆盖密钥类型的ToString()或通过实现TypeConverter来自定义。 在反序列化字典时,TypeConverter还将支持再次转换自定义字符串。

我找到了一个有用的示例,说明如何在Microsoft的“操作方法”页面上实现这种类型的转换器:

  • 实现类型转换器 (请参见类型转换器以进行值转换)。

本质上,我需要扩展System.ComponentModel.TypeConverter并覆盖:

 bool CanConvertFrom(ITypeDescriptorContext context, Type source); object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value); object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType); 

还有必要将属性 [TypeConverter(typeof(MyClassConverter))]MyClass类声明中。

有了这些,我就能够自动序列化和反序列化字典。

一切都比较容易

 var details = new Dictionary(); details.Add("Normal", new ListBaseClass { testA = "Hello", testB = "World" }); var results = Newtonsoft.Json.JsonConvert.SerializeObject(details.ToList()); var data = Newtonsoft.Json.JsonConvert.DeserializeObject> results); 

样品

  class Program { static void Main(string[] args) { var testDictionary = new Dictionary() { { new TestKey() { TestKey1 = "1", TestKey2 = "2", TestKey5 = 5 }, new TestValue() { TestValue1 = "Value", TestValue5 = 96 } } }; var json = JsonConvert.SerializeObject(testDictionary); Console.WriteLine("=== Dictionary =="); Console.WriteLine(json); // result: {"ConsoleApp2.TestKey":{"TestValue1":"Value","TestValue5":96}} json = JsonConvert.SerializeObject(testDictionary.ToList()); Console.WriteLine("=== List> =="); Console.WriteLine(json); // result: [{"Key":{"TestKey1":"1","TestKey2":"2","TestKey5":5},"Value":{"TestValue1":"Value","TestValue5":96}}] Console.ReadLine(); } } class TestKey { public string TestKey1 { get; set; } public string TestKey2 { get; set; } public int TestKey5 { get; set; } } class TestValue { public string TestValue1 { get; set; } public int TestValue5 { get; set; } }