How to make a custom converter for a filed in NEST elasticsearch

7 Views Asked by At

I have a filed which has changed from object to array of objects. So now I need to implement a custom converter to convert previous saved objects to array.

Not sure how to do it in NEST. this is what I have for newtonsoft

class SingleOrArrayConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(List<T>));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        if (token.Type == JTokenType.Array)
        {
            return token.ToObject<List<T>>();
        }
        else if (token.Type == JTokenType.Null)
        {
            return null;
        }
        return new List<T> { token.ToObject<T>() };
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        serializer.Serialize(writer, value);
    }
}


public class DTO{
        [Object(Name = "as")]
        [JsonConverter(typeof(SingleOrArrayConverter<AssociationElastic>))]
        public List<AssociationElastic> Association { get; set; }
}

Using NEST: 7.17.5

0

There are 0 best solutions below