Skip to content

System.Text.Json cannot bind to fields #69936

@SteveDunn

Description

@SteveDunn

Description

When I have a type with a JsonConstructor and some fields, I cannot deserialize JSON to that type because an exception is thrown:

System.InvalidOperationException:
   Each parameter in the deserialization constructor on type 'Steve'
   must bind to an object property or field on deserialization.

Reproduction Steps

Run this test:

        public class Steve
        {
            [JsonConstructor]
            public Steve(string a, string b, string c)
            {
                A = a;
                B = b;
                C = c;
            }

            public string A {get;}
            public string B {get; }
            public string C;
        }

        [Fact]
        public void SteveTest()
        {
            string json = @"{
    ""A"": ""a"",
    ""B"": ""b"",
    ""C"": ""c""
}";
            JsonSerializer.Deserialize<Steve>(json);
        }

Expected behavior

Either:

  • the field is bound to and no exception happens, or
  • the exception message doesn't mention the word field

Actual behavior

An exception is thrown

Regression?

No response

Known Workarounds

No response

Configuration

No response

Other information

I discovered this issue while mimicking the behaviour of S.T.J in this Pull Request.

The PR is for adding binding to immutable types in System.Configuration.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions