Search code examples
javajsonschemajson-schema-validator

jsonSchema object check for not null


Below is my json schema to validate payload for my java post api I need to make sure that for Employee Object not all properties should be null. Any one can be null but not all can be null. For example below employee object has 4 properties - empName, empAge, empAddress, empContact All 4 of these should not be null anytime. 1 or 2 or 3 out of 4 can be null. But not all 4 can be null. How can i check that ?

   "employee" :
    {
      "type": "object",
      "default": {},
       "properties": {
        "empName": {
              "type" : ["object", null]  // null is allowed
        },
        "empAge": {
              "type" : ["object", null] // null is allowed
        },
        "empAddress": {
               "type" : ["object", null]  // null is allowed
        },
        "empContact": {
               "type" : ["object", null]  // null is allowed
          } 
       }
    }   

tried using anyOf & other jsonSchema validations but didn't worked


Solution

  • First, the null type also needs to be set in quotes: "type": [ "object", "null" ]

    Regarding your second requirement. I am afraid you need to check that at least one of the properties is set:

    "anyOf": [
      { "properties": "empName": { "type": "object" } },
      { "properties": "empAge": { "type": "object" } },
      { "properties": "empAddress": { "type": "object" } },
      { "properties": "empContact": { "type": "object" } }
    ]