System.Text.Json.JsonSerializer 不会序列化派生类的属性

Ste*_*ane 5 .net-core

我无法让 System.Text.Json.JsonSerializer 序列化派生类的属性。Newtonsoft 完成这项工作没有任何问题。

namespace TestJson
{
    class Program
    {
        static void Main(string[] args)
        {
            var myClass = new NewClass2
            {
                Value1 = "qsd",
                ShouldBeSerialized = "why am I not serialized?"
            };

            // as expected, getting {"ShouldBeSerialized":"why am not serialized?","Value1":"qsd"}
            var textJsonSerializedFromTop = System.Text.Json.JsonSerializer.Serialize<NewClass2>(myClass);

            // expecting {"ShouldBeSerialized":"why am not serialized?","Value1":"qsd"}
            // but getting {"Value1":"qsd"}
            var textJsonSerializedFromBase = System.Text.Json.JsonSerializer.Serialize<ClassBase>(myClass);

            // as expected, getting {"ShouldBeSerialized":"why am not serialized?","Value1":"qsd"}
            var newtonSoftSerializedFromBase = Newtonsoft.Json.JsonConvert.SerializeObject(myClass);
        }
    }
    public class ClassBase
    {
        public string Value1 { get; set; }
    }
    public class NewClass2 : ClassBase
    {
        public string ShouldBeSerialized { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

在上一个展示实际问题的示例中,解决方案很简单,但在下面的示例中,我不知道如何通过不使用 newtonsoft 进行管理:

namespace TestJson
{
    class Program
    {
        static void Main(string[] args)
        {
            var toSerialize =
                new[] {
                    new ClassBase
                    {
                        Value1 = "aze"
                    },
                    new NewClass2
                    {
                        Value1="qsd",
                        ShouldBeSerialized="why am I not serialized?"
                    }
                 };
            var textJsonSerialized = System.Text.Json.JsonSerializer.Serialize(toSerialize);
            // expecting [{"Value1":"aze"},{"ShouldBeSerialized":"why am not serialized?","Value1":"qsd"}]
            // but getting [{"Value1":"aze"},{"Value1":"qsd"}]
            Console.WriteLine(textJsonSerialized);

            var newtonSoftSerialized =  Newtonsoft.Json.JsonConvert.SerializeObject(toSerialize);
            // as expected getting [{"Value1":"aze"},{"ShouldBeSerialized":"why am not serialized?","Value1":"qsd"}]

            Console.WriteLine(newtonSoftSerialized);
        }
    }
    public class ClassBase
    {
        public string Value1 { get; set; }
    }
    public class NewClass2 : ClassBase
    {
        public string ShouldBeSerialized { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)