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

任何帮助表示赞赏

最佳答案

使用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用于这些类型,因此除非您要更改该转换器上的其他设置,否则无需为它们注册转换器。

关于elasticsearch - Nest 2.x-自定义JsonConverter,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37203442/

10-13 02:09