Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

c# - Why does System.Text Json Serialiser not serialise this generic property but Json.NET does?

I have the following situation. I have simplified the problem into the following example, although my real situation is more complicated.

System.Text.Json does not serialise the object fully but Newtonsoft Json.NET does.

Suppose I have the following class structure.

public class A
{
    public string AProperty { get; set; } = "A";
}

public class A<T> : A where T : class, new()
{
    public T TObject { get; set; } = new T();
}

public class B
{
    public string BProperty { get; set; } = "B";
}

public class B<T> : B where T : class, new()
{
    public T TObject { get; set; } = new T();
}

public class C
{
    public string CProperty { get; set; } = "C";
}

Here is a simple .NET Core program:

public class Program
{
    private static void Main(string[] args)
    {
        var obj = new A<B> { TObject = new B<C>() };

        var systemTextSerialized = JsonSerializer.Serialize(obj);
        var newtonsoftSerialized = JsonConvert.SerializeObject(obj);
    }
}

The serialised results are as follows:

System.Text.Json

{
  "TObject": {
    "BProperty": "B"
  },
  "AProperty": "A"
}

Newtonsoft

{
  "TObject": {
    "TObject": {
      "CProperty": "C"
    },
    "BProperty": "B"
  },
  "AProperty": "A"
}

Due to the structure of my application, I don't know the generic parameter of B. I only know that it is an A<B>. The actual TObject of B is not known until runtime.

Why do these two serialisation methods differ? Is there a way to get System.Text.Json to serialise the object fully, or do I need to write a custom converter?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a documented limitation of System.Text.Json. From the docs:

Serialize properties of derived classes

Serialization of a polymorphic type hierarchy is not supported. For example, if a property is defined as an interface or an abstract class, only the properties defined on the interface or abstract class are serialized, even if the runtime type has additional properties. The exceptions to this behavior are explained in this section....

To serialize the properties of [a] derived type, use one of the following approaches:

  1. Call an overload of Serialize that lets you specify the type at runtime...

  2. Declare the object to be serialized as object.

In your case A<B>.TObject is declared to be of type B but is actually of type B<C> in the instance you construct, so only the properties of the base class B are getting serialized as per the documentation. So that's that. For further discussion see the closed issue System.Text.Json.JsonSerializer doesn't serialize properties from derived classes #31742.

There are several workarounds available, however. Firstly, you could construct obj as its most possibly derived type A<B<C>>:

var obj = new A<B<C>> { TObject = new B<C>() };

Now all properties of TObject get serialized. Demo fiddle #1 here. But unfortunately you can't use this workaround since The actual TObject of B is not known until runtime.

Alternatively, if you only need to serialize your obj, you could follow suggestion #2 from the docs and declare an object-typed surrogate property, and serialize that:

public class A<T> : A where T : class, new()
{
    [System.Text.Json.Serialization.JsonPropertyName("TObject")]
    [Newtonsoft.Json.JsonIgnore]
    public object SerializedTObject => TObject;

    [System.Text.Json.Serialization.JsonIgnore]
    public T TObject { get; set; } = new T();
}

Note that JsonSerializerOptions.IgnoreReadOnlyProperties must not be set for read-only properties to be serialized.

Demo fiddle #2 here.

Finally, if you need polymorphic serialization and deserialization, you will need to write a custom JsonConverter. To get started see


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...