Nest 2.x - 自定义JsonConverter [英] Nest 2.x - Custom JsonConverter
问题描述
我想使用Newtonsoft的IsoDateTimeConverter来格式化我的DateTime属性的json版本。
I want to use the IsoDateTimeConverter from Newtonsoft to format the json version of my DateTime properties.
但是,我不知道Nest 2中是如何完成的。 x。
However, I cant figure out how this is done in Nest 2.x.
这是我的代码:
var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var settings = new ConnectionSettings(connectionPool, s => new MyJsonNetSerializer(s));
var client = new ElasticClient(settings);
public class MyJsonNetSerializer : JsonNetSerializer
{
public MyJsonNetSerializer(IConnectionSettingsValues settings) : base(settings) { }
protected override void ModifyJsonSerializerSettings(JsonSerializerSettings settings)
{
settings.NullValueHandling = NullValueHandling.Ignore;
}
protected override IList<Func<Type, JsonConverter>> ContractConverters => new List<Func<Type, JsonConverter>>()
{
type => new Newtonsoft.Json.Converters.IsoDateTimeConverter()
};
}
我收到这个例外:
message: "An error has occurred.",
exceptionMessage: "Unexpected value when converting date. Expected DateTime or DateTimeOffset, got Nest.SearchDescriptor`1[TestProject.DemoProduct].",
exceptionType: "Elasticsearch.Net.UnexpectedElasticsearchClientException"
任何
推荐答案
与 Func< Type,JsonConverter>
您需要检查您要注册的转换器的类型是否正确;如果是,则返回转换器实例,否则返回 null
with the Func<Type, JsonConverter>
, you need to check that the type is the right one for the converter that you want to register; if it is, return the converter instance, otherwise return null
public class MyJsonNetSerializer : JsonNetSerializer
{
public MyJsonNetSerializer(IConnectionSettingsValues settings) : base(settings) { }
protected override void ModifyJsonSerializerSettings(JsonSerializerSettings settings)
{
settings.NullValueHandling = NullValueHandling.Ignore;
}
protected override IList<Func<Type, JsonConverter>> ContractConverters => new List<Func<Type, JsonConverter>>()
{
type =>
{
return type == typeof(DateTime) ||
type == typeof(DateTimeOffset) ||
type == typeof(DateTime?) ||
type == typeof(DateTimeOffset?)
? new Newtonsoft.Json.Converters.IsoDateTimeConverter()
: null;
}
};
}
NEST使用 IsoDateTimeConverter
对于这些类型,默认情况下,您不需要为其注册转换器,除非您想更改转换器上的其他设置。
NEST uses the IsoDateTimeConverter
for those types by default, so you won't need to register a converter for them unless you would like to change other settings on the converter.
这篇关于Nest 2.x - 自定义JsonConverter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!