gpt4 book ai didi

c# - json.net 使用 CamelCasePropertyNamesContractResolver 错误地转换 TimeZoneInfo

转载 作者:太空宇宙 更新时间:2023-11-03 15:52:44 24 4
gpt4 key购买 nike

当我尝试使用 CamelCasePropertyNamesContractResolver 将 TimeZoneInfo 对象转换为 JToken 时,我的单元测试失败了。没有一个属性名称是小写的。奇怪的是,这只会影响 TimeZoneInfo 而不会影响其他类,如 KeyValuePair(我测试过的类)。我不确定是我做错了还是 json.net 的错误。我已经在 C#4.0 中用旧版本和最新版本 6.0.3 尝试过它,两者都表现出相同的行为。

  [TestMethod]
public void TimeZoneInfoConvertedCorrectly()
{
JToken actual2 = JToken.FromObject(new KeyValuePair<string, string>("test", "test2"), JsonSerializer.Create(
new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }));

// these don't fail
Assert.AreEqual(new JValue("test"), actual2["key"]);
Assert.AreEqual(new JValue("test2"), actual2["value"]);

JToken actual = JToken.FromObject(TimeZoneInfo.Utc, JsonSerializer.Create(
new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }));
// should fail but doesn't, right?
Assert.IsNull(actual["BaseUtcOffset"], "All the properties should be camel cased");
}

最佳答案

TimeZoneInfo 未使用 Json.NET 的对象转换器进行序列化。而是使用ISerializable 接口(interface)的GetObjectData 方法的实现。反序列化时,使用私有(private)构造函数。显然,.NET 框架不关心您为 Json.NET 设置的选项。

在序列化任何类型的实现ISerializable 的对象时,您的设置将被忽略,具有手动读/写属性的自定义 JSON 转换器等。

如果要自定义此类类型的序列化,则需要编写自定义转换器。

关于c# - json.net 使用 CamelCasePropertyNamesContractResolver 错误地转换 TimeZoneInfo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25129826/

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