using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text.Json.Serialization;
public class ItemConverterDecorator<TItemConverter> : JsonConverterFactory where TItemConverter : JsonConverter, new()
readonly TItemConverter itemConverter = new TItemConverter();
public override bool CanConvert(Type typeToConvert) => GetItemType(typeToConvert).ItemType is var itemType && itemType != null && itemConverter.CanConvert(itemType);
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
var (itemType, isArray, isSet) = GetItemType(typeToConvert);
throw new NotImplementedException();
return (JsonConverter)Activator.CreateInstance(typeof(ArrayItemConverterDecorator<>).MakeGenericType(typeof(TItemConverter), itemType), new object [] { options, itemConverter })!;
if (!typeToConvert.IsAbstract && !typeToConvert.IsInterface && typeToConvert.GetConstructor(Type.EmptyTypes) != null)
return (JsonConverter)Activator.CreateInstance(typeof(ConcreteCollectionItemConverterDecorator<,,>).MakeGenericType(typeof(TItemConverter), typeToConvert, typeToConvert, itemType), new object [] { options, itemConverter })!;
var setType = typeof(HashSet<>).MakeGenericType(itemType);
if (typeToConvert.IsAssignableFrom(setType))
return (JsonConverter)Activator.CreateInstance(typeof(ConcreteCollectionItemConverterDecorator<,,>).MakeGenericType(typeof(TItemConverter), setType, typeToConvert, itemType), new object [] { options, itemConverter })!;
var listType = typeof(List<>).MakeGenericType(itemType);
if (typeToConvert.IsAssignableFrom(listType))
return (JsonConverter)Activator.CreateInstance(typeof(ConcreteCollectionItemConverterDecorator<,,>).MakeGenericType(typeof(TItemConverter), listType, typeToConvert, itemType), new object [] { options, itemConverter })!;
return (JsonConverter)Activator.CreateInstance(typeof(EnumerableItemConverterDecorator<,>).MakeGenericType(typeof(TItemConverter), typeToConvert, itemType), new object [] { options, itemConverter })!;
static (Type? ItemType, bool IsArray, bool isSet) GetItemType(Type type)
if (type.IsPrimitive || type == typeof(string) || typeof(IDictionary).IsAssignableFrom(type))
return (null, false, false);
return type.GetArrayRank() == 1 ? (type.GetElementType(), true, false) : (null, false, false);
foreach (var iType in type.GetInterfacesAndSelf())
var genType = iType.GetGenericTypeDefinition();
if (genType == typeof(ISet<>))
else if (genType == typeof(IEnumerable<>))
var thisItemType = iType.GetGenericArguments()[0];
if (itemType != null && itemType != thisItemType)
return (null, false, false);
else if (genType == typeof(IDictionary<,>))
return (null, false, false);
return (itemType, false, isSet);
abstract class CollectionItemConverterDecoratorBase<TEnumerable, TItem> : JsonConverter<TEnumerable> where TEnumerable : IEnumerable<TItem>
readonly JsonConverter<TItem> innerConverter;
public CollectionItemConverterDecoratorBase(JsonSerializerOptions options, TItemConverter converter)
var modifiedOptions = new JsonSerializerOptions(options);
modifiedOptions.Converters.Insert(0, converter);
innerConverter = (JsonConverter<TItem>)modifiedOptions.GetConverter(typeof(TItem));
protected TCollection BaseRead<TCollection>(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) where TCollection : ICollection<TItem>, new()
if (reader.TokenType != JsonTokenType.StartArray)
throw new JsonException();
var list = new TCollection();
if (reader.TokenType == JsonTokenType.EndArray)
var item = innerConverter.Read(ref reader, typeof(TItem), options);
public sealed override void Write(Utf8JsonWriter writer, TEnumerable value, JsonSerializerOptions options)
writer.WriteStartArray();
foreach (var item in value)
innerConverter.Write(writer, item, options);
sealed class ArrayItemConverterDecorator<TItem> : CollectionItemConverterDecoratorBase<TItem [], TItem>
public ArrayItemConverterDecorator(JsonSerializerOptions options, TItemConverter converter) : base(options, converter) { }
public override TItem [] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => BaseRead<List<TItem>>(ref reader, typeToConvert, options).ToArray();
sealed class ConcreteCollectionItemConverterDecorator<TCollection, TEnumerable, TItem> : CollectionItemConverterDecoratorBase<TEnumerable, TItem>
where TCollection : ICollection<TItem>, TEnumerable, new()
where TEnumerable : IEnumerable<TItem>
public ConcreteCollectionItemConverterDecorator(JsonSerializerOptions options, TItemConverter converter) : base(options, converter) { }
public override TEnumerable Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => BaseRead<TCollection>(ref reader, typeToConvert, options);
sealed class EnumerableItemConverterDecorator<TEnumerable, TItem> : CollectionItemConverterDecoratorBase<TEnumerable, TItem> where TEnumerable : IEnumerable<TItem>
public EnumerableItemConverterDecorator(JsonSerializerOptions options, TItemConverter converter) : base(options, converter) { }
public override TEnumerable Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => throw new NotImplementedException(string.Format("Deserialization is not implemented for type {0}", typeof(TEnumerable)));
public static class TypeExtensions
public static IEnumerable<Type> GetInterfacesAndSelf(this Type type) =>
(type ?? throw new ArgumentNullException()).IsInterface ? new[] { type }.Concat(type.GetInterfaces()) : type.GetInterfaces();
public class StringConverter : JsonConverter<string>
const string prefix = "foo__";
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
var s = reader.GetString();
if (s?.StartsWith(prefix) == true)
s = s.Substring(prefix.Length, s.Length - prefix.Length);
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) =>
writer.WriteStringValue(prefix + value);
public class StringModel<TCollection> where TCollection: IEnumerable<string>
[JsonConverter(typeof(ItemConverterDecorator<StringConverter>))]
public TCollection? List { get; set; }
public enum LongEnum : long
public class EnumModel<TCollection> where TCollection: IEnumerable<LongEnum>
[JsonConverter(typeof(ItemConverterDecorator<JsonStringEnumConverter>))]
public TCollection? List { get; set; }
[JsonConverter(typeof(ItemConverterDecorator<LibraryObjectConverter>))]
public List<LibraryObject> lst { get; set; } = new();
public class LibraryObject
public string? Value { get; set; }
class LibraryObjectConverter : JsonConverter<LibraryObject>
const string prefix = "foo__";
public override LibraryObject Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
var s = reader.GetString();
if (s?.StartsWith(prefix) == true)
s = s.Substring(prefix.Length, s.Length - prefix.Length);
return new LibraryObject { Value = s };
public override void Write(Utf8JsonWriter writer, LibraryObject value, JsonSerializerOptions options) =>
writer.WriteStringValue(prefix + value.Value);
public static void Test()
var expectedJson = @"{""lst"":[""foo__one"",""foo__two""]}";
lst = new () { new LibraryObject { Value = "one" }, new LibraryObject { Value = "two" } },
var json = JsonSerializer.Serialize(data);
var data2 = JsonSerializer.Deserialize<Data>(json);
var json2 = JsonSerializer.Serialize(data2);
Assert.AreEqual(json, json2);
Assert.IsTrue(data.lst.Select(l => l.Value).SequenceEqual(data.lst.Select(l => l.Value)));
Assert.AreEqual(expectedJson, json);
static void TestEnumRoundTrips()
Console.WriteLine((long)LongEnum.SixtyThree);
var expectedJson = @"{""List"":[""Zero"",""One"",""SixtyThree""]}";
TestEnumRoundTrip(new [] { LongEnum.Zero, LongEnum.One, LongEnum.SixtyThree }, expectedJson);
TestEnumRoundTrip(new List<LongEnum> { LongEnum.Zero, LongEnum.One, LongEnum.SixtyThree }, expectedJson);
TestEnumRoundTrip<IList<LongEnum>>(new List<LongEnum> { LongEnum.Zero, LongEnum.One, LongEnum.SixtyThree }, expectedJson);
TestEnumRoundTrip<ICollection<LongEnum>>(new List<LongEnum> { LongEnum.Zero, LongEnum.One, LongEnum.SixtyThree }, expectedJson);
TestEnumRoundTrip<IEnumerable<LongEnum>>(new List<LongEnum> { LongEnum.Zero, LongEnum.One, LongEnum.SixtyThree }, expectedJson);
TestEnumRoundTrip(new HashSet<LongEnum> { LongEnum.Zero, LongEnum.One, LongEnum.SixtyThree }, expectedJson);
TestEnumRoundTrip<ISet<LongEnum>>(new HashSet<LongEnum> { LongEnum.Zero, LongEnum.One, LongEnum.SixtyThree }, expectedJson);
TestEnumRoundTrip(new Collection<LongEnum> { LongEnum.Zero, LongEnum.One, LongEnum.SixtyThree }, expectedJson);
TestEnumRoundTrip(new ObservableCollection<LongEnum> { LongEnum.Zero, LongEnum.One, LongEnum.SixtyThree }, expectedJson);
TestEnumRoundTrip(new SortedSet<LongEnum> { LongEnum.Zero, LongEnum.One }, @"{""List"":[""Zero"",""One""]}");
TestEnumRoundTrip(new [] { LongEnum.Zero, LongEnum.One | LongEnum.SixtyThree }, @"{""List"":[""Zero"",""One, SixtyThree""]}" );
TestEnumRoundTrip(new SortedSet<LongEnum> { LongEnum.Zero, LongEnum.One }, @"{""List"":[""Zero"",""One""]}");
TestEnumRoundTrip(default(LongEnum []), @"{""List"":null}" );
public static void TestEnumRoundTrip<TCollection>(TCollection? list, string expectedJson) where TCollection: IEnumerable<LongEnum>
Console.WriteLine("Testing declared type {0}", typeof(TCollection));
var model = new EnumModel<TCollection> { List = list };
var json = JsonSerializer.Serialize(model);
if (expectedJson != null)
Assert.AreEqual(expectedJson, json);
var model2 = JsonSerializer.Deserialize<EnumModel<TCollection>>(json);
var json2 = JsonSerializer.Serialize(model2);
Assert.AreEqual(json, json2);
Assert.IsTrue(model2 != null && ((model.List == null && model2.List == null) || (model.List != null && model2.List != null && model.List.SequenceEqual(model2.List))));
static void TestStringRoundTrips()
var expectedJson = @"{""List"":[""foo__a"",""foo__b""]}";
TestStringRoundTrip(new [] { "a", "b" }, expectedJson);
TestStringRoundTrip(new List<string> { "a", "b" }, expectedJson);
TestStringRoundTrip<IList<string>>(new List<string> { "a", "b" }, expectedJson);
TestStringRoundTrip<ICollection<string>>(new List<string> { "a", "b" }, expectedJson);
TestStringRoundTrip<IEnumerable<string>>(new List<string> { "a", "b" }, expectedJson);
TestStringRoundTrip(new HashSet<string> { "a", "b" }, expectedJson);
TestStringRoundTrip<ISet<string>>(new HashSet<string> { "a", "b" }, expectedJson);
TestStringRoundTrip(new SortedSet<string> { "a", "b" }, expectedJson);
TestStringRoundTrip(new Collection<string> { "a", "b" }, expectedJson);
TestStringRoundTrip(new ObservableCollection<string> { "a", "b" }, expectedJson);
TestStringRoundTrip((List<string>)null!, @"{""List"":null}");
public static void TestStringRoundTrip<TCollection>(TCollection list, string expectedJson) where TCollection: IEnumerable<string>
Console.WriteLine("Testing declared type {0}", typeof(TCollection));
var model = new StringModel<TCollection> { List = list };
var json = JsonSerializer.Serialize(model);
Assert.AreEqual(expectedJson, json);
var model2 = JsonSerializer.Deserialize<StringModel<TCollection>>(json);
var json2 = JsonSerializer.Serialize(model2);
Assert.AreEqual(expectedJson, json2);
Assert.IsTrue(model2 != null && ((model.List == null && model2.List == null) || (model.List != null && model2.List != null && model.List.SequenceEqual(model2.List))));
public static void Main()
Console.WriteLine("Environment version: {0} ({1}), {2}", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion(), Environment.OSVersion);
Console.WriteLine("System.Text.Json version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");
public static string GetNetCoreVersion()
var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
var assemblyPath = assembly.Location.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];