Re:Ask HN: Do you use JSON Schema? Help us shape its future ...
by petilon on Monday January 30, 2023 @07:57PM
(#34589258)
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-do...
Re:Ask HN: Do you use JSON Schema? Help us shape its future ...
by magicalhippo on Monday January 30, 2023 @11:05PM
(#34590885)
I 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/...
[2]: https://json-schema.org/understanding-json-schema/reference/...
Re:Ask HN: Do you use JSON Schema? Help us shape its future ...
by com2kid on Tuesday January 31, 2023 @03:57PM
(#34601954)
You are doing it correctly.
Re:Ask HN: Do you use JSON Schema? Help us shape its future ...
by com2kid on Tuesday January 31, 2023 @03:57PM
(#34601946)
> 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.
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