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

How can I serialize/deserialize a dictionary with custom keys using Json.Net?(如何使用 Json.Net 序列化/反序列化带有自定义键的字典?)
本文介绍了如何使用 Json.Net 序列化/反序列化带有自定义键的字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有以下类,用作字典中的键:

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 对象数组,而不是字典.

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(...) 调用检索字典.

Here you deserialize the array and then retrieve the dictionary with .ToDictionary(...) call.

我不确定输出是否符合您的期望,但肯定它通过了相等性断言.

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

这篇关于如何使用 Json.Net 序列化/反序列化带有自定义键的字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Force JsonConvert.SerializeXmlNode to serialize node value as an Integer or a Boolean(强制 JsonConvert.SerializeXmlNode 将节点值序列化为整数或布尔值)
Using JSON to Serialize/Deserialize TimeSpan(使用 JSON 序列化/反序列化 TimeSpan)
Could not determine JSON object type for type quot;Classquot;(无法确定类型“Class的 JSON 对象类型.)
How to deserialize a JSONP response (preferably with JsonTextReader and not a string)?(如何反序列化 JSONP 响应(最好使用 JsonTextReader 而不是字符串)?)
how to de-serialize JSON data in which Timestamp it-self contains fields?(如何反序列化时间戳本身包含字段的JSON数据?)
JSON.Net custom contract serialization and Collections(JSON.Net 自定义合约序列化和集合)