我有 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/