Repository navigation
Description
Background and motivation
As part of migrating the Microsoft Store to System.Text.Json, we have several cases where we cannot change the exact JSON schema being used, as it would cause older versions of the client to no longer work correctly. This means we have to structure some of our System.Text.Json-based models to account for some Newtonsoft.Json-specific quirks.
As an example, consider this JSON response:
{
"A": {
"$type": "System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.String, mscorlib]], mscorlib",
"Foo": "Bar",
"Baz": "Blah"
},
"B": {
"$type": "System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Collections.Generic.IList`1[[System.String, mscorlib]], mscorlib]], mscorlib",
"Foo": [ "Bar", "Baz" ],
"Blah": [ "Hello" ]
}
}Note those two $type properties. This is needed because older clients are deserializing this response with an unstructured approach, and those type discriminators are needed to ensure the deserialized objects have the correct type. If we move this to a System.Text.Json model though, we'd instead end up with something like this:
public sealed class SomeResponse
{
public Dictionary<string, string>? A { get; set; }
public Dictionary<string, List<string>>? B { get; set; }
}This has several issues though:
- In the "A" case, the dictionary will end up having an additional (incorrect) "$type" key.
- In the "B" case, that will outright fail to deserialize, because the value of "$type" can't be converted to a
List<string>.
One approach could be to manually write a custom converter for each of these properties, but that's rather verbose, error prone, and it just overall adds a lot of complexity for something that would be nice to just work "out of the box".
I don't have an exact API shape in mind to address this, so opening this more of a discussion, but would it be possible to consider adding some way (eg. some [JsonIgnoreTypeDiscriminator] attribute on the property) to instruct the serializer to ignore the "$type" property, if present, and have it not affect the deserialization of the actual property?
In case this is already possible and I just haven't figured out why, even better 😄
cc. @eiriktsarpalis
Activity
eiriktsarpalis commentedon Feb 13, 2023
This appears to be a duplicate of #79059, I think it might be solvable using something like this #79059 (comment)