Skip to content

System.Text.Json polymorphism strange behaviour? #101454

Answered by elgonzo
nsoderberg asked this question in Q&A
Discussion options

You must be logged in to vote

So why are the results different to begin with?

The reason is the different type of the serialized variables t1 (object) and t2 (InventoryPurchase). Per the polymorphic serialization guide at https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/polymorphism:

Important

For polymorphic serialization to work, the type of the serialized value should be that of the polymorphic base type. This includes using the base type as the generic type parameter when serializing root-level values, as the declared type of serialized properties, or as the collection element in serialized collections.

In your second case,

var s2 = JsonSerializer.Serialize(t2);

infers Inventory…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@nsoderberg
Comment options

Answer selected by nsoderberg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants