简体   繁体   中英

How to use dependentRequired with relative reference in JSON schema

I have below JSON schema in my app, and i am using NewtonSoft JSON schema validation library to validate user JSON against my schema.

The rules that i need to set are -

  1. if user sets property2 in the JSON then property3 should also exist and subProperty2 should also exist underneath property3 .
  2. if user does not set property2 then property3 is not required.

I used dependentRequired for this with relative reference using period(.) but that did not work with NewtonSoft package. I tried in 2 different ways, both without expected result.

{
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "property1": {
      ...
    },
    "property2": {
      ...
    },
    "property3": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "subProperty1": {
          ...
        },
        "subProperty2": {
          ...
        },
      }
    }
  },
   "required": [
    "property1"
  ]
}

//try 1

  "dependentRequired": {
    "property2": [ "property3.subProperty2" ]
  },

//try 2

  "dependentRequired": {
    "property2": {
      "required": [ "property3" ],
      "property3": {
        "required": [ "subProperty2" ]
      }
    }
  } 

Can someone help me with this?

The dot notation used in the first try is not supported in JSON Schema.

The second try is the right idea, but since you are using a schema, you need to use dependentSchemas instead of dependentRequired . Also, you are missing the properties keyword to make that a valid schema.

  "dependentSchemas": {
    "property2": {
      "required": [ "property3" ],
      "properties": {
        "property3": {
          "required": [ "subProperty2" ]
        }
      }
    }
  },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM