Skip to content

System.Text.Json unable to deserialize an object that implement IEnumerable but is itself not a list #81084

@RyanGaudion

Description

@RyanGaudion

Description

JsonSerializer.Deserialize is unable to deserialize a class that contains it's own properties will also implementing IEnumerable

Reproduction Steps

Please see the test code here:

    public class UnitTest1
    {
        [Fact]
        public void Test1()
        {
            string validJson = @"
{
    ""List1"": [{""Test"": ""a""}],
    ""List2"": [{""Test"": ""a""}]
}";

            MyClass obj = JsonSerializer.Deserialize<MyClass>(validJson);

        }
    }
    class MyClass //: IEnumerable<TestClass>
    {
        public List<TestClass> List1 { get; set; } = new List<TestClass>();
        public List<TestClass> List2 { get; set; } = new List<TestClass>();

        public IEnumerator<TestClass> GetEnumerator()
        {
            return List1.Concat(List2).GetEnumerator();
        }
        //IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
    }

    class TestClass
    {
        public string Test { get; set; }
    }

This code passes, but when uncommenting out the 2 comments in MyClass - the tests then fail.

Expected behavior

I expected adding an interface and method to an object to not effect it's ability to be deserialized

Actual behavior

The deserialization fails with this error System.Text.Json.JsonException : The JSON value could not be converted to MyClass. Path: $ | LineNumber: 1 | BytePositionInLine: 1.

Regression?

No response

Known Workarounds

No response

Configuration

No response

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Text.Jsonneeds-further-triageIssue has been initially triaged, but needs deeper consideration or reconsideration

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions