-1

I have an dictionary that is serialized as an array of arrays:

"values":[["key1",0], ["key2", 0]]

My goal is to deserialize it to Dictionary<string, int>, eventually List<KeyValuePair<string, int>> using an JsonConverterAttribute from System.Text.Json with custom Converter. I tried to do it on my own, but failed.

halfer
  • 19,824
  • 17
  • 99
  • 186
SzejkM8
  • 9
  • 1
  • 1

1 Answers1

1

I made it work. I'm posting this if anyone else need this in the future.

    public class ArraySyntaxToDictionaryConverter : JsonConverter<Dictionary<string, int>>
    {
        public override Dictionary<string, int> Read(
            ref Utf8JsonReader reader,
            Type typeToConvert,
            JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.Null)
            {
                return null;
            }

            var output = new Dictionary<string, int>();

            while (reader.Read() && reader.TokenType != JsonTokenType.EndArray)
            {
                if (reader.TokenType != JsonTokenType.StartArray)
                {
                    throw new JsonException();
                }

                while (reader.Read() && reader.TokenType != JsonTokenType.EndArray)
                {
                    if (reader.TokenType != JsonTokenType.String)
                    {
                        throw new JsonException();
                    }
                    var key = reader.GetString();

                    if (!reader.Read() || reader.TokenType != JsonTokenType.Number)
                    {
                        throw new JsonException();
                    }
                    var value = reader.GetInt32();
                    output[key] = value;
                }
            }

            if (reader.TokenType != JsonTokenType.EndArray)
            {
                throw new JsonException();
            }

            return output;
        }

        public override void Write(
            Utf8JsonWriter writer,
            Dictionary<string, int> value,
            JsonSerializerOptions options)
        {
            throw new NotImplementedException();
        }
    }

Decorate the property as follow

[JsonPropertyName("values"), JsonConverter(typeof(ArraySyntaxToDictionaryConverter))]
public Dictionary<string, int> Values { get; set; }
SzejkM8
  • 9
  • 1
  • 1