[System.Text.Json] : More accurate error messages when failing to map fields or parameters #88048
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:
- When the name cannot be matched, then Give the name of the offender, i.e. the name of the parameter that could not be bound.
Could not bind parameter 'id' in constructor (Guid, string, string)
- When the type cannot be matched (but the name was found) then give BOTH the expected type and the found type, side by side.
Parameter 'category' with type Guid could not be bound to property 'Category' with type Nullable<Guid>.
the code performing those checks can be found here ;
https://source.dot.net/#System.Text.Json/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.cs,572
API Proposal
API Usage
Alternative Designs
No response
Risks
No response
Activity