Skip to content

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

Closed

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

Activity

  1. ghost added
    untriaged
    on Jan 24, 2023
  2. krwq commented on Jan 24, 2023

    @krwq
    Member

    You'll need to implement CustomConverter for your type.

    The reason this is not serializable is following:

  3. added
    needs-author-action
    on Jan 24, 2023
  4. ghost removed
    untriaged
    on Jan 24, 2023
  5. added this to the Future milestone on Jan 24, 2023
  6. krwq commented on Jan 24, 2023

    @krwq
    Member

    Marking as needs-author-action because given current information we should close this issue as duplicate. Please close or add further details (bot will automatically close this issue if there is no response)

  7. RyanGaudion commented on Jan 25, 2023

    @RyanGaudion
    Author

    @krwq thank you for the reference to #63791. This looks like it'll resolve the issue. Is there any workaround to get an implementation like #63791 working with a custom converter? If so, what would this converter look like?

  8. ghost added
    needs-further-triage
    on Jan 25, 2023
  9. ghost removed
    needs-author-action
    on Jan 25, 2023
  10. krwq commented on Jan 25, 2023

    @krwq
    Member

    Implementation could look something like this (done very minimal testing on that, just showing idea):

    class MyClassConverter : JsonConverter<MyClass>
    {
        public override MyClass? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            MyClass obj = new();
    
            while (reader.TokenType != JsonTokenType.EndObject)
            {
                if (reader.TokenType == JsonTokenType.PropertyName)
                {
                    string? propertyName = reader.GetString();
                    reader.Read();
                    List<TestClass>? list = JsonSerializer.Deserialize<List<TestClass>>(ref reader, options);
                    if (propertyName == nameof(MyClass.List1))
                    {
                        obj.List1 = list;
                    }
                    else if (propertyName == nameof(MyClass.List2))
                    {
                        obj.List2 = list;
                    }
                    else
                    {
                        // we ignore unknown properties by default
                    }
                }
    
                reader.Read();
            }
    
            return obj;
        }
    
        public override void Write(Utf8JsonWriter writer, MyClass value, JsonSerializerOptions options)
        {
            writer.WriteStartObject();
            writer.WritePropertyName(nameof(MyClass.List1));
            JsonSerializer.Serialize(writer, value.List1, options);
            writer.WritePropertyName(nameof(MyClass.List2));
            JsonSerializer.Serialize(writer, value.List2, options);
            writer.WriteEndObject();
        }
    }

    then you add that to options which you pass to Serialize/Deserialize:

    JsonSerializerOptions options = new()
    {
        Converters = { new MyClassConverter() }
    };
  11. ghost locked as resolved and limited conversation to collaborators on Feb 24, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Text.Jsonneeds-further-triage

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions