且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-29 22:57:49

这应该可以解决问题:

序列化:

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.