Search code examples
javascriptjsonjson.netschemajsonschema

How to use "oneOf" in this schema?


I'd like to have either A or B, but not both (mutual exclusive.)

I have to use whatever is avaliable in Draft 3, even though it says 4 on the top. Reason being, when using array for "required", it throws an error that it can't convert an array to a boolean. If I remove arrays without putting that I'm using draft 4 [Newtonsoft.Json.Schema.Extensions]::IsValid does not validate. It returns "true" willy nilly.

Yes, I have to use an obsolete Newtonsoft.

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "description": "",
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "SearchCriteria": {
      "type": "array",
      "uniqueItems": true,
      "minItems": 1,
      "required": true,
      "items": {
        "type": "object",
        "additionalProperties": false,
        "properties": {
          "A": {
            "type": "string",
            "minLength": 1,
            "pattern": "^[^\\s]*$"
          },
          "B": {
            "type": "array",
            "items": {
              "type": "string",
              "minLength": 1,
              "pattern": "^[^\\s]*$",
              "enum": ["One", "Two"]
            },
            "minItems": 1
          },
          "C": {
            "type": "string",
            "required": true,
            "minLength": 2
          },
          "D": {
            "type": "array",
            "required": true,
            "items": {
              "type": "string"
            },
            "minItems": 1,
            "uniqueItems": true
          }
        }
      }
    }
  }
}

Solution

  • Draft 3 does not support OneOf or any of the likes as @dbc mentioned in a comment.

    [Newtonsoft.Json.Schema.JsonSchema] uses draft 3 to prase the JSON file. Hence why it was ignoring OneOf AND throwing an error for "required" being an array. In draft 3, "required" can only be a boolean.

    To overcome this, use [Newtonsoft.Json.Schema.JSchema] to parse the Schema as a string and [Newtonsoft.Json.Linq.JToken] to parse the JSON as a string, and [Newtonsoft.Json.Schema.SchemaExtensions] to validate isntead of [Newtonsoft.Json.Schema.Extensions].