我使用JsonSchema.Net(docs)根据准备好的模式来验证JSON文档.一些属性在模式中被定义为可为空(as described in the documentation,{"oneOf":[{"type":"string"},{"type":"null"}]}
)
当我对照模式判断文档时,一些可为空的属性的计算细节将返回IsValid = false
,错误与JSON中的错误相反(例如"Value is "null" but should be "integer""
或"Value is "number" but should be "null""
).
我想知道在这种情况下我可能做错了什么.我如何过滤这种误报,以便如果Json文档无效,我可以快速找到导致这些错误的 node ,以及它们的问题所在.
文档示例:
{
"referenceNumber": "35366",
"storageZone": null,
"maxCount": null,
"length": 124.5
}
文档的Json架构:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Schema Example",
"$defs": {
"stringNullable": {
"oneOf": [
{ "type": "string" },
{ "type": "null" }
]
},
"integerNullable": {
"oneOf": [
{ "type": "integer" },
{ "type": "null" }
]
},
"numberNullable": {
"oneOf": [
{ "type": "number" },
{ "type": "null" }
]
}
},
"type": "object",
"properties": {
"referenceNumber": {
"type": "string"
},
"storageZone": {
"$ref": "#/$defs/stringNullable"
},
"maxCount": {
"$ref": "#/$defs/integerNullable"
},
"length": {
"$ref": "#/$defs/numberNullable"
}
}
}
代码示例:
[Test]
public void JsonSchemaAsserts()
{
var schema = JsonSchema.FromFile("./SchemaExample.json");
var jsonText = File.ReadAllText("./DataExample.json");
var json = JsonNode.Parse(jsonText);
var validationResult = schema.Evaluate(json, new EvaluationOptions() { OutputFormat = OutputFormat.List });
Assert.That(validationResult.IsValid, Is.True);
var validationErrors = validationResult.Details.Where(d => !d.IsValid && d.HasErrors).ToList();
Assert.That(validationResult, Is.Empty);
}