简体   繁体   English

C# 多态 JSON 反序列化字典/列表对象

[英]C# Polymorphic JSON deserialization for Dictionary/List objects

I need to deserialize dynamic JSON text that can represent either System.Collections.Generic.Dictionary<string, T> or System.Collections.Generic.List< T>.我需要反序列化可以表示 System.Collections.Generic.Dictionary<string, T> 或 System.Collections.Generic.Generic 的动态 JSON 文本。 I suppose I have to write custom converter but I'm not sure about how it should look like properly.我想我必须编写自定义转换器,但我不确定它应该看起来如何正确。 I'm using .NET5's System.Text.Json.我正在使用 .NET5 的 System.Text.Json。

Sample JSON for dictionary type (sent almost all the time):字典类型的示例 JSON(几乎一直发送):

{
"1":
    {
       "13346964555":
          {
              "data1":1,
              "data2":2
          },
        "13346964556":
          {
              "data1":1,
              "data2":2
          },
     }
}

Sample JSON for list type (rare, needs to be converted into dictionary with empty string keys):列表类型的示例 JSON(很少见,需要转换为空字符串键的字典):

{
"1": [
     {
        "data1":1,
        "data2":2
     },
     {
        "data1":1,
        "data2":2
     }
   ]
}

On the other side, converting from normal dictionary to list of its values is acceptable as well, since I don't need keys at all currently.另一方面,从普通字典转换为其值列表也是可以接受的,因为我目前根本不需要键。

ended up with this converter, from Dictionary to List, based on another example.最终得到了这个转换器,从字典到列表,基于另一个例子。 seems to work fine in my case.在我的情况下似乎工作正常。 feel free to discuss if something is wrong here.如果这里有问题,请随时讨论。 note that I only need to convert specific dictionary type, so no need for converters' factory here.请注意,我只需要转换特定的字典类型,所以这里不需要转换器的工厂。

public class DictionaryToListConverter : JsonConverter<List<type>>
{
    public override bool CanConvert(Type typeToConvert)
    {
        return typeof(List<type>) == typeToConvert;
    }

    public override List<type> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        bool is_array = reader.TokenType == JsonTokenType.StartArray;
        bool is_dictionary = reader.TokenType == JsonTokenType.StartObject;

        if (is_array || is_dictionary)
        {
            var list = new List<type>();

            while (reader.Read())
            {
                if ((is_array && reader.TokenType == JsonTokenType.EndArray) || (is_dictionary && reader.TokenType == JsonTokenType.EndObject))
                    return list;

                if (is_dictionary)
                {
                    if (reader.TokenType != JsonTokenType.PropertyName)
                        throw new JsonException();

                    reader.Read(); // skip the key and move to value.
                }

                list.Add(JsonSerializer.Deserialize<type>(ref reader));
            }
        }

        throw new JsonException();
    }

    public override void Write(Utf8JsonWriter writer, List<type> value, JsonSerializerOptions options)
    {
        // ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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