3 ms·
> Also lack of inheritance support. (For example I want a way to specify that my json object should be deserialized as Dog not as Animal.) Use Typescript, then
by com2kid 4y ago
> Also lack of inheritance support. (For example I want a way to specify that my json object should be deserialized as Dog not as Animal.)
Use Typescript, then so long as it barks, you can treat it like a dog!
And if it knows how to bark and meow, you can treat it as a dog or a cat at your leisure. :-D
- petilon 4y agoThe 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.