巢2.X - 自定义JsonConverter(Nest 2.x - Custom JsonCon

2019-09-29 18:06发布

我想用从Newtonsoft的IsoDateTimeConverter格式化我的DateTime属性的JSON版本。

然而,我无法弄清楚如何在鸟巢做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"

任何帮助表示赞赏

Answer 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;
        }
    };
}

NEST使用IsoDateTimeConverter这些类型在默认情况下,这样你就不会需要注册一个转换器,用于它们,除非你想在转换器更改其它设置。



文章来源: Nest 2.x - Custom JsonConverter