dotnet/runtime

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

Open

#88.048 aperta il 26 giu 2023

Vedi su GitHub
 (12 commenti) (10 reazioni) (0 assegnatari)C# (5445 fork)batch import
area-System.Text.Jsonenhancementhelp wanted

Metriche repository

Star
 (17.886 star)
Metriche merge PR
 (Merge medio 12g 11h) (661 PR mergiate in 30 g)

Descrizione

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

Guida contributor