如何在NJsonSchema C#中使用JSON模式验证JSON [英] How to validate json with json schema in NJsonSchema c#

查看:554
本文介绍了如何在NJsonSchema C#中使用JSON模式验证JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为合同测试的一部分,我必须验证从rest-endpoint获得的json响应是否存在于文件中的json-schema.我正在使用NJsonSchema,但无法执行此操作.

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模式如下

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'}

任何人都可以通过示例(使用示例)来阐明如何使用NJsonSchema或Manatee.Json通过jsonschema验证json.

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

推荐答案

免责声明:我是Manatee.Json的作者.

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

这看起来像一个 draft-03 模式(required关键字已从 draft-04 的属性声明中移出).我不确定NJsonSchema是否支持旧版本的架构.海牛,杰森没有.

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模式当前位于 draft-07 ,而 draft-08 即将发布.

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

我的建议是通过将required关键字移到根中作为properties的同级元素,将架构重写为以后的草案. required的值成为包含所需属性列表的字符串数组.

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" ]
}

这样做,肯定可以与Manatee.Json一起使用,而且我期望也可以与NJsonSchema一起使用.

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

如果您有关于使用Manatee.Json的特定问题,请在我的Slack工作区打我. GH自述文件上有一个链接.

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

这篇关于如何在NJsonSchema C#中使用JSON模式验证JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆