验证失败,但缺少错误消息

时间:2020-06-19 20:13:33

标签: manatee.json

我正在尝试使用以下代码针对特定架构验证JSON文件:

string data = File.ReadAllText("../../../testFiles/create.json");
string schemaText = File.ReadAllText("../../../schemas/request-payload.schema.json");
var serializer = new JsonSerializer();
var json = JsonValue.Parse(data);
var schema = serializer.Deserialize<JsonSchema>(JsonValue.Parse(schemaText));
var result = schema.Validate(json);
Assert.IsTrue(result.IsValid);

断言失败,因为result.IsValid为false(这是正确的-我的JSON中有故意的错误),但没有指示错误发生的地方:

enter image description here

我的架构在definition部分中确实有子模式。可以和它有什么关系吗?我需要设置一些属性来查看该错误信息吗?

更新:添加了架构并测试JSON

我的原始模式长了几百行,但是我将其缩减为仍然存在问题的子集。这是模式:

{
    "$schema": "https://json-schema.org/draft/2019-09/schema#",
    "$id": "request-payload.schema.json",
    "type": "object",
    "propertyNames": { "enum": ["template" ] },
    "required": ["template" ],
    "properties": {
        "isPrivate": { "type": "boolean" },
        "template": {
            "type": "string",
            "enum": [ "TemplateA", "TemplateB" ]}},
    "oneOf": [
        {
            "if": {
                "properties": { "template": { "const": "TemplateB" }}},
            "then": { "required": [ "isPrivate" ] }}]
}

这是一个测试JSON对象:

{   
      "template": "TemplateA"
}

上面的JSON可以很好地验证。将值切换为TemplateB,并且JSON验证失败(因为isPrivate丢失,并且对于TemplateB来说是必需的),但是结果不包含任何有关失败原因的信息。

上面列出了我用于运行验证测试的代码

1 个答案:

答案 0 :(得分:1)

该问题可能是您尚未设置输出格式。 The default format is flag,这意味着您只会获得对值是否通过的真假判断。

要获取更多详细信息,您需要使用其他格式设置。您可以通过schema options进行此操作。

例如:

JsonSchemaOptions.OutputFormat = SchemaValidationOutputFormat.Detailed;

可用选项为here