我有一個復雜的檔案,它在各種不同的子鍵中有一個自定義日期欄位,即:
var doc = new Document
{
MyCustomDateTime StartTime
Matches = new []
{
MyCustomDateTime StartTime
MyCustomDateTime EndTime
}
}
不使用屬性屬性,因為這種型別是從 dll 中提取的,我可以覆寫 type 的序列化和反序列化的最簡單方法是什么MyCustomDateTime。
我正在尋找類似于或擴展默認序列化程式類以處理另一種型別的東西:
settings.DefaultSerializerFor<MyCustomDateTime>(d => MyConverter.ToString(d), d => MyConverter.FromString(d));
或類似的東西:
public class MyCustomSerializer : DefaultElasticSearchSerializer
{
public string OnSerialize(object member)
{
if (member is MyCustomDateTime) { return MyConverter.ToString(d); }
return base.OnSerialize(member);
}
...
}
現在,它似乎只發布物件的公共屬性。不幸的是,對于這個特定的課程,這不是我正在尋找的行為。
uj5u.com熱心網友回復:
實作自定義序列化的最簡單方法是
- 連接JsonNetSerializer
- 為您的型別定義轉換器
- 使用 JsonNetSerializer 注冊它
一個例子
private static void Main()
{
var defaultIndex = "default_index";
var pool = new SingleNodeConnectionPool(new Uri($"http://localhost:9200"));
var settings = new ConnectionSettings(
pool,
(builtin, settings) => new JsonNetSerializer(builtin, settings, contractJsonConverters: new List<JsonConverter>
{
new MyCustomDateTimeConverter()
}))
.DefaultIndex(defaultIndex);
var client = new ElasticClient(settings);
var indexResponse = client.Index(
new MyDocument {
Message = "message",
CustomDateTime = new MyCustomDateTime
{
Custom = new DateTimeOffset(2022,1,9,14,0,0,0, TimeSpan.FromHours(10))
}
}, i => i.Id(1));
}
public class MyCustomDateTime
{
public DateTimeOffset Custom { get; set; }
}
public class MyCustomDateTimeConverter : JsonConverter<MyCustomDateTime>
{
public override void WriteJson(JsonWriter writer, MyCustomDateTime value, JsonSerializer serializer)
{
writer.WriteValue(value.Custom);
}
public override MyCustomDateTime ReadJson(JsonReader reader, Type objectType, MyCustomDateTime existingValue, bool hasExistingValue, JsonSerializer serializer)
{
var dateTime = reader.ReadAsDateTimeOffset();
return dateTime is null ? null : new MyCustomDateTime { Custom = dateTime.Value };
}
}
public class MyDocument
{
public string Message {get;set;}
public MyCustomDateTime CustomDateTime {get;set;}
}
產量
PUT http://localhost:9200/default_index/_doc/1?pretty=true
{
"message": "message",
"customDateTime": "2022-01-09T14:00:00 10:00"
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/408448.html
標籤:
上一篇:彈性停止分析器和模糊搜索問題
下一篇:Elasticsearch例外[type=parsing_exception,reason=[wildcard]查詢不支持[case_insensitive]]
