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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…