简体   繁体   中英

Cannot serialize Dictionary in C#

I am passing in a request model as a parameter to my API for a POST request and one of the properties on the request model is of type Dictionary<int, OrderFood>. I'm using Swagger to test the action methods and the error response I get is:

"The collection type 'System.Collections.Generic.Dictionary`2[System.int32, OrderFood] is not supported.'"

I understand that there isn't currently support for serializing a non-string key Dictionary and that I need to implement a custom JSON converter. This is the request model class:

    [JsonConverter(typeof(JsonNonStringKeyDictionaryConverter<int, OrderFood>))]
public class FoodOrderRequestModel
{
    public string ModelName { get; set; }

    public string DisplayName { get; set; }

    public string Type { get; set; }

    public object ModelValue { get; set; }

    public object DisplayValue { get; set; }

    public Dictionary<int, OrderFood> Items { get; set; }
}

And here is the converter:

internal sealed class JsonNonStringKeyDictionaryConverter<TKey, TValue> : JsonConverter<IDictionary<TKey, TValue>>
{
    public override IDictionary<TKey, TValue> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var convertedType = typeof(Dictionary<,>)
            .MakeGenericType(typeof(string), typeToConvert.GenericTypeArguments[1]);
        var value = JsonSerializer.Deserialize(ref reader, convertedType, options);
        var instance = (Dictionary<TKey, TValue>)Activator.CreateInstance(
            typeToConvert,
            BindingFlags.Instance | BindingFlags.Public,
            null,
            null,
            CultureInfo.CurrentCulture);
        var enumerator = (IEnumerator)convertedType.GetMethod("GetEnumerator")!.Invoke(value, null);
        var parse = typeof(TKey).GetMethod("Parse", 0, BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Any, new[] { typeof(string) }, null);
        if (parse == null)
        {
            throw new NotSupportedException($"{typeof(TKey)} as TKey in IDictionary<TKey, TValue> is not supported.");
        }

        while (enumerator.MoveNext())
        {
            var element = (KeyValuePair<string?, TValue>)enumerator.Current;
            instance.Add((TKey)parse.Invoke(null, new[] { element.Key }), element.Value);
        }

        return instance;
    }

    public override void Write(Utf8JsonWriter writer, IDictionary<TKey, TValue> value, JsonSerializerOptions options)
    {
        var convertedDictionary = new Dictionary<string?, TValue>(value.Count);
        foreach (var (k, v) in value)
        {
            convertedDictionary[k?.ToString()] = v;
        }

        JsonSerializer.Serialize(writer, convertedDictionary, options);
        convertedDictionary.Clear();
    }
}

internal sealed class JsonNonStringKeyDictionaryConverterFactory : JsonConverterFactory
{
    public override bool CanConvert(Type typeToConvert)
    {
        if (!typeToConvert.IsGenericType)
        {
            return false;
        }

        if (typeToConvert.GenericTypeArguments[0] == typeof(string))
        {
            return false;
        }

        return typeToConvert.GetInterface("IDictionary") != null;
    }

    public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
    {
        var converterType = typeof(JsonNonStringKeyDictionaryConverter<,>)
            .MakeGenericType(typeToConvert.GenericTypeArguments[0], typeToConvert.GenericTypeArguments[1]);
        var converter = (JsonConverter)Activator.CreateInstance(
            converterType,
            BindingFlags.Instance | BindingFlags.Public,
            null,
            null,
            CultureInfo.CurrentCulture);
        return converter;
    }
}

Serialization happens before any break point is hit on my API so I'm not sure how I can test my converter to see if its even added into the pipeline. I'm also uncertain of the placement of the JsonNonStringKeyDictionaryConverter<,> because I've seen certain implementations where it is directly above the attribute. Any advice or help is greatly appreciated.

Update/Add your System.Text.Json NuGet package to the LTS version 5.0.1 Worked well for a .NET Core 3.1 application.

Special thanks to @CoolBots with the topic discussion on github https://github.com/dotnet/runtime/issues/30524#issuecomment-524619972

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM