Nest 2.x - 自定义JsonConverter

时间:2016-05-13 07:09:47

标签: elasticsearch nest

我想使用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"

感谢任何帮助

1 个答案:

答案 0 :(得分:2)

使用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;
        }
    };
}

NEST默认使用IsoDateTimeConverter作为这些类型,因此您不需要为它们注册转换器,除非您想要更改转换器上的其他设置。