Custom JSON converter for the OpenSearchClient

53 Views Asked by At

Background: I have in the OpenSearch inconsistent data. Sometimes a given property is a string and sometimes it's a list of strings. I don't have a control over that.

When using System.Text.Json serializer I can create a custom JSON converter that automatically converts a list of strings into a string with comma separated values. I can add an attribute above a property that needs to be deserialized in a desired way and it does the magic.

How do I get the same functionality with the .Net's OpenSearch client serializer?

Here is the code that I use for System.Text.Json serializer

using Serilog;
using System;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace myProject
{
    public class ListOfStringToStringConverter : JsonConverter<string>
    {
        public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.Null) return null;
            string strValue = "";
            try
            {
                if (JsonTokenType.String == reader.TokenType)
                {
                    strValue = reader.GetString();
                    return strValue;
                }
                else if (JsonTokenType.StartArray == reader.TokenType)
                {
                    reader.Read();
                    string val = "";
                    int i = 0;
                    while (reader.TokenType != JsonTokenType.EndArray)
                    {
                        if (i != 0) val += ",";
                        val += reader.GetString();
                        i++;
                        reader.Read();
                    }
                    return val;
                }
            }
            catch (Exception e)
            {
                Log.Error(e, "Problem during deserializing JSON value to a property. Property value will be set to null");
            }
            return null;
        }

        public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
        {
            if (value == null)
            {
                writer.WriteStringValue("null");
            }
            else
            {
                writer.WriteStringValue(value);
            }
        }
    }
}
[System.Text.Json.Serialization.JsonConverter(typeof(ListOfStringToStringConverter))]
public string? ItUsedToBeAList { get; set; }
1

There are 1 best solutions below

0
Michael Nelson On

Unfortunately the OpenSearch .NET client uses Utf8json for serialization so you'll need to do the custom conversion with Utf8json instead. There are a few other issues related to serialization on the OpenSearch .NET client. Hopefully it moves to System.Text.Json or supports using whichever serializer anyone wants in the future.