gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:55:50 24 4
gpt4 key购买 nike

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

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

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

    [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 是:

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

这显然是错误的。我怎样才能让它发挥作用?

最佳答案

这应该可以解决问题:

序列化:

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

调用 expected.ToArray()你正在序列化 KeyValuePair<MyClass, object> 的数组对象而不是字典。

反序列化:

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

在这里反序列化数组,然后用 .ToDictionary(...) 检索字典打电话。

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

关于c# - 如何使用 Json.Net 序列化/反序列化带有自定义键的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24681873/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com