4 ms·
The issue is when JSON has to be parsed on the server using Java/C#. How do you know whether to parse it as a Dog or as a Cat (both of which inherits from Anima
by petilon 4y ago
The issue is when JSON has to be parsed on the server using Java/C#. How do you know whether to parse it as a Dog or as a Cat (both of which inherits from Animal)?
Here's Microsoft's workaround:
https://devblogs.microsoft.com/dotnet/system-text-json-in-dotnet-7/#using-type-discriminators https://devblogs.microsoft.com/dotnet/system-text-json-in-do...
- magicalhippo 4y agoI must admit I'm a noob in this world so maybe I'm going about it the wrong way, but I used JSON Schema's oneOf[1] along with required[2] for this: "properties": { "cat": { "$ref": "#/$defs/catType" } "dog": { "$ref": "#/$defs/dogType" } }, "oneOf": [ { "required": ["cat"] }, { "required": ["dog"] }, ] Usage would then look like: { "dog": { "name": "Charlie" } } At least it's explicit and can be easily checked for validity. [1]: https://json-schema.org/understanding-json-schema/reference/combining.html#oneof https://json-schema.org/understanding-json-schema/reference/... [2]: https://json-schema.org/understanding-json-schema/reference/object.html#required-properties https://json-schema.org/understanding-json-schema/reference/...
- com2kid 4y agoYou are doing it correctly. https://en.wikipedia.org/wiki/Tagged_union https://en.wikipedia.org/wiki/Tagged_union
- com2kid 4y ago> The issue is when JSON has to be parsed on the server using Java/C#. How do you know whether to parse it as a Dog or as a Cat (both of which inherits from Animal)? I mean how MS does it, yeah, you have a tagged union, look at the tag to determine what it is. Heck even networking packets work this way, UDP or TCP, look at the Protocol Field on the IP packet to see which it is.