0

I am working on a Blazor app that uses the local storage. I want to JSON serialize this data-structure:

datastucture

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?

k.c.
  • 1,755
  • 1
  • 29
  • 53
  • 1
    You will need to use a custom `JsonConverter` as shown in [Is polymorphic deserialization possible in System.Text.Json?](https://stackoverflow.com/q/58074304/3744182). In fact that looks to be a duplicate, agree? See also the documentation page [Support polymorphic deserialization](https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to#support-polymorphic-deserialization). – dbc Mar 21 '22 at 16:59
  • any specific reason not to use json.net? I find it easier to use for cases like this. – JonasH Mar 21 '22 at 17:39
  • @jonasH I like to stay away from third party packages if there is a viable alternative on the Microsoft stack – k.c. Mar 21 '22 at 20:24
  • 1
    @dbc Looks like a duplicate indeed as far as the answer goes , although I am not migrating from Newtonsoft.Json. Probably a reason why this post was not in the list to review before posting my question. Thanks for steering me in the right direction... – k.c. Mar 21 '22 at 20:28

0 Answers0