Skip to content

[System.Text.Json] : More accurate error messages when failing to map fields or parameters #88048

Open
@mathieubergouniouxcab

Description

Background and motivation

CONTEXT:
The following issue is very common : a developer tries to deserialize some Json data into a class that has an explicit or explicit JsonConstructor, but the deserialization fails because System.Text.Json fails to map the data's property names either to an existing field in the class or to an existing parameter in the class' constructor.

It gives such errors at deserialization:
System.InvalidOperationException: Each parameter in constructor '[...]' on type '[...]' must bind to an object property or field on deserialization. Each parameter name must match with a property or field on the object. The match can be case-insensitive.

Examples of such issues can be listed with a Google query on this very tracker : site:https://github.com/dotnet/runtime/issues/ Each parameter in constructor must bind to an object property or field on deserialization

The root causes can be :

  • a discrepancy in the name,
  • a casing issue (e.g. camel case) -- that happens less often, because this can be configured
  • a type mismatch.

That last one is the trickiest one : The mismatch can be because there's a discrepancy in nullability, or in typing -- because one is an interface (e.g. IEnumerable) while the other one is a class (e.g. List). Newtonsoft was more permissive in that regard and it confuses old developers.

PROBLEM:
The error message does not give a lot of explicit details on the exact offender.

It does give a list of expected constructor parameters types. For example:
...Each parameter in constructor 'Void .ctor(System.Nullable`1[System.Guid], string, Guid, string)' ...

That's good.

PROPOSED FIX:

API Proposal

API Usage

Alternative Designs

No response

Risks

No response

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    area-System.Text.JsonenhancementProduct code improvement that does NOT require public API changes/additionshelp wanted[up-for-grabs] Good issue for external contributors

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions