Velkan Velkan - 1 month ago 11
JSON Question

JSON Schema oneOf doesn't work with references

Schema is for a message with the header properties and then either properties of

msg1
or
msg2
:

{
"$schema": "http://json-schema.org/draft-04/schema#",

"definitions": {
"header": {
"type": "object",
"properties": {
"token": { "type": "string" },
"id": { "type": "number" }
},
"required": ["token", "id"]
},
"msg1": {
"type": "object",
"properties": {
"content1": { "type": "string" }
},
"required": ["content1"]
},
"msg2": {
"type": "object",
"properties": {
"content2": { "type": "string" }
},
"required": ["content2"]
}
},

"type": "object",
"$ref": "#/definitions/header",
"oneOf": [
{"$ref": "#/definitions/msg1" },
{"$ref": "#/definitions/msg2" }
]
}


So this should pass:

{
"token": "abc123",
"id": 333,
"content1": "s"
}


The problem is that the following passes:

{
"token": "abc123",
"id": 333
}


How to fix it?

(of course, there are a lot more of
msg#
s and they have different structure)

Answer

Everything other than the $ref is getting ignored.

Any members other than "$ref" in a JSON Reference object SHALL be ignored.

You can fix the problem by wrapping $ref in an allOf.

"allOf": [{"$ref": "#/definitions/header"}],