针对JSON Schema C#验证JSON

Sha*_*ald 16 c# validation json jsonschema

有没有办法根据该结构的JSON模式验证JSON结构?我看了,发现JSON.Net验证,但这不符合我的要求.

JSON.net做:

JsonSchema schema = JsonSchema.Parse(@"{
  'type': 'object',
  'properties': {
    'name': {'type':'string'},
    'hobbies': {'type': 'array'}
  }
}");

JObject person = JObject.Parse(@"{
  'name': 'James',
  'hobbies': ['.NET', 'LOLCATS']
}");

bool valid = person.IsValid(schema);
// true
Run Code Online (Sandbox Code Playgroud)

这证实为真.

JsonSchema schema = JsonSchema.Parse(@"{
  'type': 'object',
  'properties': {
    'name': {'type':'string'},
    'hobbies': {'type': 'array'}
  }
}");

JObject person = JObject.Parse(@"{
  'surname': 2,
  'hobbies': ['.NET', 'LOLCATS']
}");

bool valid = person.IsValid(schema);
Run Code Online (Sandbox Code Playgroud)

这也证实了这一点

JsonSchema schema = JsonSchema.Parse(@"{
  'type': 'object',
  'properties': {
    'name': {'type':'string'},
    'hobbies': {'type': 'array'}
  }
}");

JObject person = JObject.Parse(@"{
  'name': 2,
  'hobbies': ['.NET', 'LOLCATS']
}");

bool valid = person.IsValid(schema);
Run Code Online (Sandbox Code Playgroud)

只有这个验证为false.

理想情况下,我希望它验证name在那里没有名称也不应该在那里的字段surname.

And*_*son 13

我认为你只需要添加

'additionalProperties': false
Run Code Online (Sandbox Code Playgroud)

到您的架构.这将阻止提供未知属性.

所以现在你的结果将是: - 真,假,假

测试代码....

void Main()
{
var schema = JsonSchema.Parse(
@"{
    'type': 'object',
    'properties': {
        'name': {'type':'string'},
        'hobbies': {'type': 'array'}
    },
    'additionalProperties': false
    }");

IsValid(JObject.Parse(
@"{
    'name': 'James',
    'hobbies': ['.NET', 'LOLCATS']
  }"), 
schema).Dump();

IsValid(JObject.Parse(
@"{
    'surname': 2,
    'hobbies': ['.NET', 'LOLCATS']
  }"), 
schema).Dump();

IsValid(JObject.Parse(
@"{
    'name': 2,
    'hobbies': ['.NET', 'LOLCATS']
  }"), 
schema).Dump();
}

public bool IsValid(JObject obj, JsonSchema schema)
{
    return obj.IsValid(schema);
}
Run Code Online (Sandbox Code Playgroud)

输出: -

True
False
False
Run Code Online (Sandbox Code Playgroud)

您还可以向必须提供的字段添加"required":true,以便您可以返回包含缺失/无效字段详细信息的消息: -

Property 'surname' has not been defined and the schema does not allow additional     properties. Line 2, position 19. 
Required properties are missing from object: name. 

Invalid type. Expected String but got Integer. Line 2, position 18. 
Run Code Online (Sandbox Code Playgroud)

  • 与其为此目的使用“additionalProperties”,目前鼓励使用“propertyNames”(自draft-06 起)。它将完成完全相同的工作(仅允许具有符合模式的 enum cor 中登记的键的属性)。另请参阅:https://json-schema.org/understanding-json-schema/reference/object.html#property-names 并考虑:`"propertyNames" : { "enum" : ["name", "hobbies"] }` 在您的架构中,而不是“additionalProperties”。 (2认同)