我如何序列化/反序列化使用Json.Net自定义键的字典?序列化、自定义、字典、Net

2023-09-03 03:48:49 作者:迩、够狠

我有以下类,我在一本字典的关键是:

I have the following class, that I use as a key in a dictionary:

    public class MyClass
    {
        private readonly string _property;

        public MyClass(string property)
        {
            _property = property;
        }

        public string Property
        {
            get { return _property; }
        }

        public override bool Equals(object obj)
        {
            MyClass other = obj as MyClass;
            if (other == null) return false;
            return _property == other._property;
        }

        public override int GetHashCode()
        {
            return _property.GetHashCode();
        }
    }

我正在运行的测试是在这里:

The test I am running is here:

    [Test]
    public void SerializeDictionaryWithCustomKeys()
    {
        IDictionary<MyClass, object> expected = new Dictionary<MyClass, object>();
        expected.Add(new MyClass("sth"), 5.2);
        JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
        string output = JsonConvert.SerializeObject(expected, Formatting.Indented, jsonSerializerSettings);
        var actual = JsonConvert.DeserializeObject<IDictionary<MyClass, object>>(output, jsonSerializerSettings);
        CollectionAssert.AreEqual(expected, actual);
    }

测试失败,因为Json.Net似乎是使用的ToString()法的字典键,而不是正确的序列化他们。从上面的测试生成的JSON是:

The test fails, because Json.Net seems to be using the ToString() method on the dictionary keys, instead of serializing them properly. The resulting json from the test above is:

{
  "$type": "System.Collections.Generic.Dictionary`2[[RiskAnalytics.UnitTests.API.TestMarketContainerSerialisation+MyClass, RiskAnalytics.UnitTests],[System.Object, mscorlib]], mscorlib",
  "RiskAnalytics.UnitTests.API.TestMarketContainerSerialisation+MyClass": 5.2
}

这显然是错误的。我怎样才能得到它的工作?

which is clearly wrong. How can I get it to work?

推荐答案

这应该做的伎俩:

连载:

JsonConvert.SerializeObject(expected.ToArray(), Formatting.Indented, jsonSerializerSettings);

通过调用 expected.ToArray()你序列化的 KeyValuePair℃的阵列; MyClass的,对象&gt; 对象而非字典

By calling expected.ToArray() you're serializing an array of KeyValuePair<MyClass, object> objects rather than the dictionary.

反序列化:

JsonConvert.DeserializeObject<KeyValuePair<IDataKey, object>[]>(output, jsonSerializerSettings).ToDictionary(kv => kv.Key, kv => kv.Value);

在这里,你反序列化数组,然后检索与词典 .ToDictionary(...)电话。

我不知道,如果输出满足您的期望,但肯定它通过平等的主张。

I'm not sure if the output meets your expectations, but surely it passes the equality assertion.