How to validate json with json schema in NJsonSchema c#

孤人 提交于 2019-12-24 09:59:13

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/50524325/how-to-validate-json-with-json-schema-in-njsonschema-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!