Loosen strict KeyValuePair deserialization logic in reflection JSON serializer to match src-gen
In the reflection serializer, both "Key" and "Value" properties exactly must be present in the object payload (otherwise JsonException is thrown), while in the src-gen implementation, any valid object payload is allowed (potentially resulting in a partially populated KVP instance). We should loosen the behavior in the reflection case for consistency.
Tagging subscribers to this area: @eiriktsarpalis, @layomia See info in area-owners.md if you want to be subscribed.
Issue Details
In the reflection serializer, both "Key" and "Value" properties exactly must be present in the object payload (otherwise JsonException is thrown), while in the src-gen implementation, any valid object payload is allowed (potentially resulting in a partially populated KVP instance). We should loosen the behavior in the reflection case for consistency.
| Author: | layomia |
|---|---|
| Assignees: | - |
| Labels: |
|
| Milestone: | 7.0.0 |
Can you give me a practical example to help me understand it? @layomia
@FatTigerWang
string json = "{}";
// JsonException thrown because "Key" and "Value" props are not both present
JsonSerializer.Deserialize<KeyValuePair<string, string>>(json);
// empty KVP returned
JsonSerializer.Deserialize(json, MyContext.Default.KeyValuePairStringString);
[JsonSerializable(typeof(KeyValuePair<string, string>))]
public partial sealed class MyContext : JsonSerializerContext { }
We want an empty KVP in both cases. I believe the solution is to remove the use of the internal KeyValuePair converter, and just let the ObjectConverterFactory create a regular SmallObjectWithParameterizedCtorConverter for KeyValuePair types.
Since most dictionary implementations require non-null keys. Assuming most KeyValuePair instances in use will eventually get fed to a dictionary-like structure, wouldn't it make sense to at least require a populated key property?
@eiriktsarpalis I think no, because it isn't the same. Usualy dictionary representation is
{
"key1":"value1",
"key2":"value2"
}
And if will be structure with KVP and it will be like that i think create empty object will be eligible behavior instead of throw. I think the logic should be the same as with regular objects
[
{},
{"Key": "key", "Value": "value"}
]
@layomia @eiriktsarpalis Are we ok with returning an empty KVP in case of NameCaseSensitive miss match? There are tests that expect the throwing exception behavior. Do we want to remove the expectation? is that it?
@eiriktsarpalis As long as I know, one can create an empty KVP and there is an exception being thrown in case
IDictionary<int, string> dictionary = new Dictionary<string, string>();
dictionary.Add(new KeyValuePair<string,string>());
So if we return an empty KVP as the result of deserialization we will meet the behavior.
Fixed by #59757.