1

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.

4
  • Can the objects have other property names that differ? In your example they all have pretty much the same structure, with just the brand property being optional. Commented Jan 30, 2018 at 18:22
  • No, they're quite different; only a couple of properties have the same name. Commented Feb 1, 2018 at 8:42
  • Hmmmm... why the downvote on the question? Commented Feb 1, 2018 at 8:42
  • Possible duplicate of Define array of multiple models in Swagger 2.0 Commented Feb 1, 2018 at 10:45

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh dear. I was afraid of that. Swagger's lack of support for these constructs is fixed in Open API 3.0 ...but we're tied to 2.0. Thanks for the reply.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.