Files
spark/src/client/spark_core/Json/JsonValueOrArrayConverter.cs
T

30 lines
1.1 KiB
C#

#nullable enable
namespace Spark.Core.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
/// <summary>
/// A JsonConverter that can parse input in the form of a (single) value, or an array.
/// </summary>
public class JsonValueOrArrayConverter<T> : JsonConverter<List<T>> {
public override List<T>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
reader.TokenType switch {
JsonTokenType.StartArray =>
reader.ReadArray(options, out var array)
? array.Select(n => n is null ? throw invalidJsonEx() : n.As<T>()).ToList()
: throw invalidJsonEx(),
JsonTokenType.Null => null,
_ => new() { JsonSerializer.Deserialize<T>(ref reader, options) ?? throw invalidJsonEx() }
};
public override void Write(Utf8JsonWriter writer, List<T> value, JsonSerializerOptions options) =>
JsonSerializer.Serialize(writer, value, options);
static JsonException invalidJsonEx() =>
new($"Failed to parse json (expected value or array of type {typeof(T)})");
}