Search code examples
c#jsonschemanjsonschema

How to validate json with json schema in NJsonSchema c#


As part of contract tests I have to validate json response I got from rest-endpoint against json-schema present in a file. I'm using NJsonSchema and was not able to perform this.

Json-schema in file is as something below

{
        'type': 'object',
        'properties': {
            'remaining': {
                'type': 'integer',
                'required': true
            },
            'shuffled': {
                'type': 'boolean',
                'required': true
            }
            'success': {
                'type': 'boolean',
                'required': true
            },
            'deck_id': {
                'type': 'string',
                'required': true
            }
        }
    }

Json I have to validate is something like below

{ 'remaining': 52, 'shuffled': true, 'success': true, 'deck_id': 'b5wr0nr5rvk4'}

Can anyone please throw some light (with examples) on how to validate json with jsonschema using NJsonSchema or Manatee.Json.


Solution

  • Disclaimer: I'm the author of Manatee.Json.

    That looks like a draft-03 schema (the required keyword was moved out of the property declaration in draft-04). I'm not sure if NJsonSchema supports schemas that old; Manatee.Json doesn't.

    JSON Schema is currently at draft-07, and draft-08 is due out soon.

    My suggestion is to rewrite the schema as a later draft by moving the required keyword into the root as a sibling of properties. The value of required becomes an array of strings containing the list of properties that are required.

    {
      "type": "object",
      "properties": {
        "remaining": { "type": "integer" },
        "shuffled": { "type": "boolean" },
        "success": { "type": "boolean" },
        "deck_id": { "type": "string" }
      },
      "required": [ "remaining", "shuffled", "success", "deck_id" ]
    }
    

    By doing this, it'll definitely work with Manatee.Json, and I expect it'll work with NJsonSchema as well.

    If you have specific questions about using Manatee.Json, hit me up on my Slack workspace. There's a link on the GH readme.