Skip to content

JsonSerializer throws InvalidCastException #2387

Description

@Fr1z2r

Using .NET Core App 3.1.101
This code throws an exception when IgnoreNullValues=true, and doesn't throw when IgnoreNullValues=false:

class MyClass
{
    public HashSet<int> X { get; set; } = new HashSet<int>();
}

public static void Main()
{
    JsonSerializer.Deserialize<MyClass>(@"{""X"":[2,1]}", 
        new JsonSerializerOptions {IgnoreNullValues = true});
}
System.InvalidCastException : Unable to cast object of type 'System.Collections.Generic.HashSet`1[System.Int32]' to type 'System.Collections.IList'.
   at System.Text.Json.JsonSerializer.ApplyObjectToEnumerable(Object value, ReadStack& state, Boolean setPropertyDirectly)
   at System.Text.Json.JsonSerializer.HandleEndArray(JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& readStack)
   at System.Text.Json.JsonSerializer.ReadCore(Type returnType, JsonSerializerOptions options, Utf8JsonReader& reader)
   at System.Text.Json.JsonSerializer.Deserialize(String json, Type returnType, JsonSerializerOptions options)
   at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions