I am working on a Blazor app that uses the local storage. I want to JSON serialize this data-structure:
The XML serializer does this without a hitch, but de JSON serializer does not include any type-info, so my C's and D's are downgraded to the base class B (and only after making B's constructor public. I have following test code:
using System.Collections.Generic;
using System.Text.Json;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TestProject;
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
// setup
var sut = new A();
sut.Bs.Add(new C{Number = 9});
sut.Bs.Add(new D{Text= "Bob"});
Assert.AreEqual(2, sut.Bs.Count);
var serialized = JsonSerializer.Serialize(sut);
// serialized: {"Bs":[{"Key":"C"},{"Key":"D"}]}
var deserialized = JsonSerializer.Deserialize<A>(serialized);
// excepiton:System.NotSupportedException:
// 'Deserialization of types without a parameterless
// constructor, a singular parameterized constructor, or a
// parameterized constructor annotated with
// 'JsonConstructorAttribute' is not supported.
}
public class A
{
public List<B> Bs { get; set; }
public A()
{
Bs = new List<B>();
}
}
public abstract class B
{
public string Key { get; init; }
public B()
{
Key = GetType().Name;
}
}
public class C : B
{
public int Number { get; set; }
public C():base()
{
}
}
public class D : B
{
public string Text { get; set; } = null!;
public D() : base()
{
}
}
}
Is there a way to make this work (attributes and or options), or do I have to make shadow properties/fields for separate lists of C's and D's?