问题
I'd like to know how to specify a JSON schema for an array of different objects. This thread gives me half the answer, but fails when I have multiple instances of each type of object.
Here's a sample XML, based on the example given here but with the "Product" object being repeated:-
{
"things": [
{
"entityType" : "Product",
"name" : "Pepsi Cola",
"brand" : "pepsi"
},
{
"entityType" : "Product",
"name" : "Coca Cola",
"brand" : "coke"
},
{
"entityType" : "Brand",
"name" : "Pepsi Cola"
}
]
}
The following schema will validate the above XML only when there is a single instance of each type (i.e. if "Product" only appears once).
{
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "https://schemas.example.com/things",
"title": "Things",
"description": "Some things",
"type": "object",
"required": [
"things"
],
"properties": {
"things": {
"type": "array",
"items": [
{
"type": "object",
"required": [
"entityType",
"name"
],
"properties": {
"entityType": {
"type": "string",
"enum": [
"Product"
]
},
"name": {
"type": "string"
},
"brand": {
"type": "string"
}
}
},
{
"type": "object",
"required": [
"entityType",
"name"
],
"properties": {
"entityType": {
"type": "string",
"enum": [
"Brand"
]
},
"name": {
"type": "string"
}
}
}
]
}
},
"additionalProperties": false
}
To add to the entertainment, I can't use keywords like "AnyOf", as I'm embedding this schema into a Swagger 2.0 document, and those keywords aren't supported.
Thanks,
J.
回答1:
Without anyOf
you're out of luck. The best you can do is use one schema that covers all of the options. It not a great solution, but it's better than nothing.
来源:https://stackoverflow.com/questions/48527444/json-schema-array-of-different-objects