gpt4 book ai didi

serialization - 尽管有 JsonSerializer 设置,SignalR 仍未序列化 NodaTime 类型

转载 作者:行者123 更新时间:2023-12-01 12:41:02 25 4
gpt4 key购买 nike

我遇到 NodaTime 类型和 SignalR 参数的序列化问题(异常),例如

Error converting value to type 'NodaTime.ZonedDateTime

Error converting value \"2016-06-01T18:33:36.7279685+01 Europe/London\" to type 'NodaTime.ZonedDateTime'. Path '[0].DateCreated', line 1, position 79.

尽管遵循了 docs并替换默认的 JsonSerializer 并使用 NodaTime 扩展方法和 JSON.net nuget 包,例如

JsonSerializerSettings js = new JsonSerializerSettings();
js.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
var serializer = JsonSerializer.Create(js);
GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);

最佳答案

很高兴从 here 中找到了解决方法感谢BrannonKing

本质上,它为 SignalR 参数使用客户解析器,该参数使用正确的序列化器而不是创建默认序列化器。

也引用了 SO here但当然只发现曾经开始发布我自己的问题;)

在此处重新发布以供其他谷歌搜索(优秀)NodaTime具体来说,并分享我需要的其他一些序列化修复,例如:

Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property X with type Y Path Z

服务器启动

public void Configuration(IAppBuilder app)
{
JsonSerializerSettings js = new JsonSerializerSettings();
js.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
js.DateParseHandling = DateParseHandling.None;
js.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
js.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
var serializer = JsonSerializer.Create(js);
GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);
var resolver = new Resolver(serializer);
GlobalHost.DependencyResolver.Register(typeof(IParameterResolver), () => resolver);
}

自定义参数解析器

public class Resolver : DefaultParameterResolver
{
private readonly JsonSerializer _serializer;

public Resolver(JsonSerializer serializer)
{
_serializer = serializer;
}

private FieldInfo _valueField;
public override object ResolveParameter(ParameterDescriptor descriptor, Microsoft.AspNet.SignalR.Json.IJsonValue value)
{
if(value.GetType() == descriptor.ParameterType)
{
return value;
}

if(_valueField == null)
_valueField = value.GetType().GetField("_value", BindingFlags.Instance | BindingFlags.NonPublic);

var json = (string)_valueField.GetValue(value);
using(var reader = new StringReader(json))
return _serializer.Deserialize(reader, descriptor.ParameterType);
}
}

非常感谢布兰农!

关于serialization - 尽管有 JsonSerializer 设置,SignalR 仍未序列化 NodaTime 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37579881/

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