Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

StackOverflow occurs when you serialize inherited objects using STJ #1588

Open
shuaqq2004 opened this issue Jan 31, 2023 · 1 comment
Open

Comments

@shuaqq2004
Copy link

CODE:

[JsonInheritanceConverter(typeof(A), "$type")]
[JsonInheritanceAttribute("B", typeof(B))]
public class A
{
    public int? X { get; set; }
}

public class B : A
{
    public int? Y { get; set; }
}

A a = new A { X = 1 };
string s = JsonSerializer.Serialize(a); //error.

Code is generated via NSwagStudio, simplified DEMO.

image

the suggestion in NET 7 , use [JsonDerivedType]

@balchen
Copy link

balchen commented May 10, 2023

I am experiencing this too.

The stack overflow happens when JsonInheritanceConverter.Read is trying to determine the subtype to deserialize. From your example, this happens when you look at type A which has a JsonInheritanceConverter attribute.

JsonInheritanceConverter.Read calls JsonInheritanceConverter.GetDiscriminatorType to get the subtype to use for deserialization. If the discriminator is not present in the serialized JSON stream, JsonInheritanceConverter.GetDiscriminatorType will return the base type (A) again.

Deserializing A will result in JsonInheritanceConverter.Read being called, and we have the endless loop causing the stack overflow.

It seems when a result type has subtypes with discriminator values, the discriminator must always be present, otherwise this endless loop will occur.

In my case, the return value is empty, but since the type is not nullable, it becomes an instance of A, serialized into JSON as {} in my case, with no discriminator, and so I see the same issue that you are seeing.

Perhaps that can help you solve your issue.

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants