Nest 2.x - Custom JsonConverter

心已入冬 提交于 2019-12-11 05:14:58

问题


I want to use the IsoDateTimeConverter from Newtonsoft to format the json version of my DateTime properties.

However, I cant figure out how this is done in Nest 2.x.

Here is my code:

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()
        };
    }

I'm getting this exception:

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"

Any help is appreciated


回答1:


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 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.



来源:https://stackoverflow.com/questions/37203442/nest-2-x-custom-jsonconverter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!