TimTheEnchanter
TimTheEnchanter

Reputation: 3671

Validation fails but error messages missing

I'm attempting to validate a JSON file against a specific schema using this code:

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);

The assertions fails because result.IsValid is false (which is correct - there is an intentional error in my JSON) but there is no indication where the error is happening:

enter image description here

My schema does have sub-schemas in the definition section. Could that have anything to do with it? Do I need to set some property to see that error information?

Update: Added schema and test JSON

My original schema was several hundred lines long, but I pared it down to a subset which still has the problem. Here is the schema:

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

And here is a test JSON object:

{   
      "template": "TemplateA"
}

The above JSON validates fine. Switch the value to TemplateB and the JSON fails validation (because isPrivate is missing and it is required for TemplateB), but the result doesn't contain any information about why it failed.

The code I'm using to run the validation test is listed above

Upvotes: -1

Views: 410

Answers (1)

gregsdennis
gregsdennis

Reputation: 8428

The issue is likely that you haven't set the output format. The default format is flag which means that you'll only get a true/false of whether the value passed.

To get more details, you'll need to use a different format setting. You can do this via the schema options.

For example:

JsonSchemaOptions.OutputFormat = SchemaValidationOutputFormat.Detailed;

The available options are here.

Upvotes: 1

Related Questions