如何使用 System.Text.Json 处理同一个 属性 的单个项目和数组?

How to handle both a single item and an array for the same property using System.Text.Json?

我正在尝试反序列化某些 JSON,其中包含的值有时是数组,有时是单个项目。我怎样才能用 System.Text.Json and JsonSerializer? (This question is inspired by this question for Json.NET by Robert McLaws.)

我收到了以下内容JSON:

[
  {
    "email": "john.doe@sendgrid.com",
    "timestamp": 1337966815,
    "category": [
      "newuser",
      "transactional"
    ],
    "event": "open"
  },
  {
    "email": "jane.doe@sendgrid.com",
    "timestamp": 1337966815,
    "category": "olduser",
    "event": "open"
  }
]

我想将其反序列化为以下类型的列表:

class Item
{
    public string Email { get; set; }
    public int Timestamp { get; set; }
    public string Event { get; set; }

    public List<string> Category { get; set; }
}

使用以下代码:

var options = new JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
var list = JsonSerializer.Deserialize<List<Item>>(json, options);

但是,当我这样做时,出现以下异常:

System.Text.Json.JsonException: The JSON value could not be converted to System.String. Path: > $[1].category | LineNumber: 13 | BytePositionInLine: 25.
   at System.Text.Json.ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType)
   at System.Text.Json.JsonPropertyInfo.Read(JsonTokenType tokenType, ReadStack& state, Utf8JsonReader& reader)
   at System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& readStack)
   at System.Text.Json.JsonSerializer.ReadCore(Type returnType, JsonSerializerOptions options, Utf8JsonReader& reader)
   at System.Text.Json.JsonSerializer.Deserialize(String json, Type returnType, JsonSerializerOptions options)
   at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)

异常是因为"category"的值有时是单个字符串,有时是字符串数组。如何用 System.Text.Json 反序列化这样的 属性?

this answer by Brian Rogers and other answers to How to handle both a single item and an array for the same property using JSON.net, you can create a generic JsonConverter<List<T>> that checks whether the incoming JSON value is an array, and if not, deserializes an item of type T and returns the item wrapped in an appropriate list. Even better, you can create a JsonConverterFactory 的启发,它为序列化图中遇到的所有列表类型 List<T> 制造了这样一个转换器

首先,定义如下转换器和转换器工厂:

public class SingleOrArrayConverter<TItem> : SingleOrArrayConverter<List<TItem>, TItem>
{
    public SingleOrArrayConverter() : this(true) { }
    public SingleOrArrayConverter(bool canWrite) : base(canWrite) { }
}

public class SingleOrArrayConverterFactory : JsonConverterFactory
{
    public bool CanWrite { get; }

    public SingleOrArrayConverterFactory() : this(true) { }

    public SingleOrArrayConverterFactory(bool canWrite) => CanWrite = canWrite;

    public override bool CanConvert(Type typeToConvert)
    {
        var itemType = GetItemType(typeToConvert);
        if (itemType == null)
            return false;
        if (itemType != typeof(string) && typeof(IEnumerable).IsAssignableFrom(itemType))
            return false;
        if (typeToConvert.GetConstructor(Type.EmptyTypes) == null || typeToConvert.IsValueType)
            return false;
        return true;
    }

    public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
    {
        var itemType = GetItemType(typeToConvert);
        var converterType = typeof(SingleOrArrayConverter<,>).MakeGenericType(typeToConvert, itemType);
        return (JsonConverter)Activator.CreateInstance(converterType, new object [] { CanWrite });
    }

    static Type GetItemType(Type type)
    {
        // Quick reject for performance
        if (type.IsPrimitive || type.IsArray || type == typeof(string))
            return null;
        while (type != null)
        {
            if (type.IsGenericType)
            {
                var genType = type.GetGenericTypeDefinition();
                if (genType == typeof(List<>))
                    return type.GetGenericArguments()[0];
                // Add here other generic collection types as required, e.g. HashSet<> or ObservableCollection<> or etc.
            }
            type = type.BaseType;
        }
        return null;
    }
}

public class SingleOrArrayConverter<TCollection, TItem> : JsonConverter<TCollection> where TCollection : class, ICollection<TItem>, new()
{
    public SingleOrArrayConverter() : this(true) { }
    public SingleOrArrayConverter(bool canWrite) => CanWrite = canWrite;

    public bool CanWrite { get; }

    public override TCollection Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        switch (reader.TokenType)
        {
            case JsonTokenType.Null:
                return null;
            case JsonTokenType.StartArray:
                var list = new TCollection();
                while (reader.Read())
                {
                    if (reader.TokenType == JsonTokenType.EndArray)
                        break;
                    list.Add(JsonSerializer.Deserialize<TItem>(ref reader, options));
                }
                return list;
            default:
                return new TCollection { JsonSerializer.Deserialize<TItem>(ref reader, options) };
        }
    }

    public override void Write(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options)
    {
        if (CanWrite && value.Count == 1)
        {
            JsonSerializer.Serialize(writer, value.First(), options);
        }
        else
        {
            writer.WriteStartArray();
            foreach (var item in value)
                JsonSerializer.Serialize(writer, item, options);
            writer.WriteEndArray();
        }
    }
}

然后在反序列化之前将转换器工厂添加到 JsonSerializerOptions.Converters

var options = new JsonSerializerOptions
{
    Converters = { new SingleOrArrayConverterFactory() },
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
var list = JsonSerializer.Deserialize<List<Item>>(json, options);

或者直接使用 JsonConverterAttribute:

将特定转换器添加到选项或数据模型
class Item
{
    public string Email { get; set; }
    public int Timestamp { get; set; }
    public string Event { get; set; }

    [JsonConverter(typeof(SingleOrArrayConverter<string>))]
    public List<string> Category { get; set; }
}

如果您的数据模型使用其他类型的集合,例如 ObservableCollection<string>,您可以应用较低级别的转换器 SingleOrArrayConverter<TCollection, TItem>,如下所示:

    [JsonConverter(typeof(SingleOrArrayConverter<ObservableCollection<string>, string>))]
    public ObservableCollection<string> Category { get; set; }

备注:

  • 如果您希望转换器仅在反序列化期间应用,请将 canWrite: false 传递给参数化构造函数:

    Converters = { new SingleOrArrayConverterFactory(canWrite: false) }
    

    转换器仍会被使用,但会无条件生成默认序列化。

  • 转换器未针对 2dnD 集合(例如 List<List<string>>)实现。它也没有为数组和只读集合实现。

  • 根据 Serializer support for easier object and collection converters #1562, because JsonConverter<T> 缺少异步 Read() 方法,

    A limitation of the existing [JsonConverter] model is that it must "read-ahead" during deserialization to fully populate the buffer up to the end up the current JSON level. This read-ahead only occurs when the async+stream JsonSerializer deserialize methods are called and only when the current JSON for that converter starts with a StartArray or StartObject token.

    因此使用此转换器反序列化可能非常大的数组可能会对性能产生负面影响。

    正如在同一线程中讨论的那样,转换器 API 可能会在 System.Text.Json - 5.0 中重新设计,以完全支持数组和对象转换器的 async 反序列化,这意味着此转换器当 .NET 5(不再标有 "Core")最终发布时,可能会受益于重写。

演示 fiddle here.

最简单的方法是使用 'object' 类型。请参阅下面的示例

    public class Example
    {
        public string Email { get; set; }
        public int Timestamp { get; set; }
        public string Event { get; set; }
        [JsonPropertyName("category")]
        public object CategoryObjectOrArray { get; set; }
        [JsonIgnore]
        public List<string> Category
        {
            get
            {
                if (CategoryObjectOrArray is JsonElement element)
                {
                    switch (element.ValueKind)
                    {
                        case JsonValueKind.Array:
                            return JsonSerializer.Deserialize<List<string>>(element.GetRawText());
                        case JsonValueKind.String:
                            return new List<string> { element.GetString() };
                    }
                }
                return null;
            }
        }
    }