2016-05-13 75 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

相關問題