一尘不染

Nest 2.x-自定义JsonConverter

elasticsearch

我想使用Newtonsoft的IsoDateTimeConverter来格式化我的DateTime属性的json版本。

但是,我无法弄清楚在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"

任何帮助表示赞赏


阅读 321

收藏
2020-06-22

共1个答案

一尘不染

使用Func<Type, JsonConverter>,您需要检查类型是否是您要注册的转换器的正确类型;如果是,则返回转换器实例,否则返回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;
        }
    };
}

IsoDateTimeConverter默认情况下,NEST 对这些类型使用,因此除非您要更改转换器上的其他设置,否则无需为它们注册转换器。

2020-06-22