2016-05-13 66 views
1

我想使用Newtonsoft的IsoDateTimeConverter来格式化我的DateTime属性的json版本。Nest 2.x - 自定义JsonConverter

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

任何帮助表示赞赏

回答

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这些类型在默认情况下,这样你就不会需要注册一个转换器,用于它们,除非你想在更改其他设置转换器。

+0

谢谢 - 它非常有意义 – Rasmus

相关问题