0

Try validate JsonSchema in Json response by C#/Newtonsoft with method response.IsValid(schema, out IList<string> messages); Looks like items from array are ignored. I dont understand, why schema:

{
  "type": "object",
  "properties": {
    "balance": {
      "type": "number"
    },
    "bonuses": {
      "type": "array",
      "items": [
        {
          "type": "object",
          "properties": {
            "bonusAmount": {
              "type": "number"
            },
            "bonusID": {
              "type": "integer"
            }
          },
          "required": [
            "bonusAmount",
            "bonusID"
          ]
        }
      ]
    }
  },
  "required": [
    "balance",
    "bonuses"
  ]
}

Valid for response { "balance": 40.0, "bonuses": [ ] } I tried a few online validators as well and result the same - schema is valid for current response.

Serge
  • 40,935
  • 4
  • 18
  • 45
  • Can you give an example of an instance that isn't validating as you expect? The one you posted doesn't have any items. – gregsdennis Feb 17 '23 at 18:24
  • As the `bonuses` array is empty, there is no element that could violate the schema... If you want to ensure that the array is not empty see https://stackoverflow.com/questions/16583485/how-to-define-the-min-size-of-array-in-the-json-schema – derpirscher Feb 17 '23 at 18:29
  • I expected the validation process should be failed and response.IsValid(schema, out IList messages) returned 'false'. But I get 'true'. – OleksiiK Feb 17 '23 at 18:34
  • Why exactly would you expect your example to fail? – derpirscher Feb 17 '23 at 18:40
  • If I want to check that response contains an array of 'bonuses' and that they're matched with schema. But if I get a response with an empty array - my test with response.IsValid is not failed as expected. Or is it an unsuitable approach for my goal? – OleksiiK Feb 17 '23 at 18:47
  • I'll try to rephrase a little. The task is to check that the response contains an array of bonuses corresponding to the scheme. But a response may come in which the array will be empty. Can I solve such a check by checking the schema of the response, or is it incorrect to solve this by checking the schema? – OleksiiK Feb 17 '23 at 18:55
  • Yes, but not really. I would also like to check the schemas of the array elements. – OleksiiK Feb 17 '23 at 19:06
  • Your schema is fine for that. Just at the `minLength` for your array. If there are elements in your array, the validation will check their structure – derpirscher Feb 17 '23 at 19:21
  • You need to add `minItems`, not minLength. – Clemens Feb 20 '23 at 09:10

0 Answers0