I develop a small program which allows to serialize/deserialize a class in Json.
This program, I make it .NET 7 and therefore I use System.Text.Json
So I have an ITest interface. This interface is implemented in two classes TestSuite and TestCase.
[JsonDerivedType(typeof(TestSuite), "testSuite")]
[JsonDerivedType(typeof(TestCase), "testCase")]
[JsonPolymorphic(UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToNearestAncestor)]
public interface ITest
{
}
public class TestCase : ITest
{
public string Name { get; set; }
}
public class TestSuite : ITest, IEnumerable<ITest>
{
private readonly List<ITest> _tests = new ();
public void Add(ITest test)
{
_tests.Add(test);
}
/// <inheritdoc />
public IEnumerator<ITest> GetEnumerator()
{
return _tests.GetEnumerator();
}
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
And to test, I do:
ITest suite = new TestSuite { new TestCase { Name = "Oui" }, new TestCase { Name = "Test2" } };
string json = JsonSerializer.Serialize(suite);
var s = JsonSerializer.Deserialize<ITest>(json);
Console.WriteLine(json);
TestCase serialization and deserialization works perfectly.
But for TestSuite deserialization fails with error message:
System.NotSupportedException: 'The collection type 'Test.TestSuite' is abstract, an interface, or is read only, and could not be instantiated and populated. Path: $.$values | LineNumber: 0 | BytePositionInLine: 32.'
I can't use custom JsonConverter because json polymorphism only supports json converter by default.
Do you know how I could solve this problem?
Thanks in advance,
I tried to create a custom JsonConverter for TestSuite but I can't. Then I tried to abort json polymorphism and create a custom JsonConverter for ITest but this is not a good idea.