CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Text.Json.Nodes;
//https://stackoverflow.com/questions/77557549/configuring-which-type-that-fields-of-type-ilist-get-when-deserializing-json
using NUnit.Framework; // Throws NUnit.Framework.AssertionException
class MyClass{
public IList<NestedClass> MyList { get; set; }
}
class NestedClass{
public IList<AnotherNestedClass> NestedList { get; set; }
}
class AnotherNestedClass{
public string SomeValue { get; set; }
}
#nullable enable
public class IListAsObservableCollectionConverter : JsonConverterFactory
{
public override bool CanConvert(Type typeToConvert) =>
typeToConvert.IsInterface && typeToConvert.IsGenericType && typeToConvert.GetGenericTypeDefinition() == typeof(IList<>);
public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) =>
(JsonConverter)Activator.CreateInstance(typeof(IListAsObservableCollectionConverterGeneric<>).MakeGenericType(typeToConvert.GetGenericArguments()))!;
class IListAsObservableCollectionConverterGeneric<T> : JsonConverter<IList<T>>
{
public override void Write(Utf8JsonWriter writer, IList<T> value, JsonSerializerOptions options) =>
JsonSerializer.Serialize(writer, value, value.GetType(), options);
public override IList<T>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
JsonSerializer.Deserialize<ObservableCollection<T>>(ref reader, options);
}
}
class TestClass
{
public static void Test()
{
var expectedJson =
"""
{
"MyList": [
{
"NestedList": [
{
"SomeValue": "value 1"
},
{
"SomeValue": "value 2"
}
]
}
]
}
""";
var options = new JsonSerializerOptions
{
Converters = { new IListAsObservableCollectionConverter() },
// Other options as required, e.g.:
IncludeFields = true, // Required to serialize & deserialize public fields as well as properties.
WriteIndented = true,
};
var inputModel = new MyClass
{
MyList = new ObservableCollection<NestedClass>()
{
new()
{
NestedList = new ObservableCollection<AnotherNestedClass>()
{
new() { SomeValue = "value 1" }, new() { SomeValue = "value 2" },
},
},
},
};
var json = JsonSerializer.Serialize(inputModel, options);
Console.WriteLine("Input JSON:");
Console.WriteLine(json);
var obj = JsonSerializer.Deserialize<MyClass>(json, options);
Console.WriteLine(obj?.MyList?.GetType()); // This should be ObservableCollection<NestedClass>
var json2 = JsonSerializer.Serialize(obj, options);
Assert.AreEqual(typeof(ObservableCollection<NestedClass>), obj?.MyList?.GetType());
Assert.That(obj!.MyList.Select(c => c?.NestedList?.GetType()).All(t => t == typeof(ObservableCollection<AnotherNestedClass>)));
Assert.That(inputModel.MyList.SelectMany(c => c.NestedList).Select(c2 => c2.SomeValue).SequenceEqual(
obj!.MyList.SelectMany(c => c.NestedList).Select(c2 => c2.SomeValue)));
Assert.AreEqual(expectedJson, json);
Assert.AreEqual(expectedJson, json2);
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Environment version: {0} ({1}), {2}", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion);
Console.WriteLine("System.Text.Json version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
}
}