json schema validation. How can I accept an array or null?
.net, c#, json
Solution
You can specify an array of possible types like so;
"myProperty": { "type": [ "array", "null" ], "required":false }
The json will pass validation if "myProperty" is of any type in the type's array. I set required to false because you said this was an optional property, that will only make it pass if the property is not present in the json. If you have required set to false and the property is in the json but of the wrong type, validation will fail.
These are the best docs on json schemas that I know of; http://json-schema.org/latest/json-schema-validation.html The site lacks useful examples but any details that you need will be in the docs.
Problem
We have implemented json schema validation (using newtonsoft) on our rest layer. It's really made a difference, but I have a question of possibility and how to. For a specific property, the following is valid (according to the product owner): .... choices: [] ....... .... choices: ["hello", "world"] .... choices: null ..... here is a whittled down example of the json schema definition ``` { 'description': 'myDescription', 'type': 'object', 'properties': { 'name': {'type':'string', 'required': true}, 'description': {'type':'string'}, 'choices': {'type': 'array', 'items': {'type': 'string'}} } ``` Obviously the first 2 examples pass validation, but the latter fails with "expecting an array" error. The property is optional. As an aside, if anyone has a good link to the full set of documentation on json schema definitions, I'd love to get it. I have not found a good single source, but I am sure there is one. Thank you. -r