Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Unknown subtype causes Stackoverflow exception at deserialization #1728

Open
ryanheath opened this issue Sep 7, 2024 · 0 comments · May be fixed by #1729
Open

Unknown subtype causes Stackoverflow exception at deserialization #1728

ryanheath opened this issue Sep 7, 2024 · 0 comments · May be fixed by #1729

Comments

@ryanheath
Copy link

See example code & payload

[JsonInheritanceConverter(typeof(Event), "$type")]
[JsonInheritanceAttribute("Arrival", typeof(Arrival))]
[JsonInheritanceAttribute("Departure", typeof(Departure))]
public partial class Event
{
}

public partial class Data
{
    [JsonPropertyName("events")]
    public ICollection<Event> Events { get; set; } = new System.Collections.ObjectModel.Collection<Event>();
}

{ "events": [{"$type":"Cancel"}] }

trying to deserialize the payload with a (yet) unknown subtype "Cancel" causes a stackoverflow exception.

I think the problem is with the generated JsonInheritanceConverter<TBase>.GetObjectSubtype.
It always returns a value but it should return null when it cannot find any known subtype.

private System.Type GetObjectSubtype(System.Type objectType, string discriminator)
{
    foreach (var attribute in System.Reflection.CustomAttributeExtensions.GetCustomAttributes<JsonInheritanceAttribute>(System.Reflection.IntrospectionExtensions.GetTypeInfo(objectType), true))
    {
        if (attribute.Key == discriminator)
            return attribute.Type;
    }

    return objectType;  // <--- this should return null!
}

The only place where GetObjectSubtype is called is in JsonInheritanceConverter<TBase>.GetDiscriminatorType which tests for null(!) ...

When the fix (returning null when subtype is not found) is applied the code throws the correct exception

throw new System.InvalidOperationException("Could not find subtype of '" + objectType.Name + "' with discriminator '" + discriminatorValue + "'.");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant