0

How can I print SchemaValidationResults in a human readable format (e.g. JSON)? Documentation page talks about different output formats (JsonSchemaOptions.OutputFormat property), but I cannot figure out how to get to text representation.

My code has the following pattern:

JsonSchema schema = _SchemaReader.Get(schemaPath);
JsonValue json = JsonValue.Parse(jsonDoc);
SchemaValidationResults validationResult = schema.Validate(json, new JsonSchemaOptions()
{
    OutputFormat = SchemaValidationOutputFormat.Detailed
});

validationResult.Should().BeValid(); // Custom FluentAssertions extension

Custom FluentAssertions extension code:

// Subject is SchemaValidationResults
Execute.Assertion.
    Given(() => Subject).
    ForCondition(s => s.IsValid).
    FailWith("Validation Errors: {0}", Subject.ErrorMessage);

But the resulting error message is: "Items at indices [2,4] failed validation." But I would like to see a more comprehensive output.

GKalnytskyi
  • 579
  • 7
  • 16

2 Answers2

1

The output is a recursive structure per draft 2019-09. This means that further results are contained within the top-level structure.

In your case, you're looking for errors, so you need to look in the validationResult.NestedResults (previous edit had .Errors) property. Here you will find the additional details you want.


Alternatively, you can change the output format to a flat list by setting JsonSchemaOptions.OutputFormat = SchemaValidationOutputFormat.Basic;. This is also one of the output formats detailed in the specification.

gregsdennis
  • 7,218
  • 3
  • 38
  • 71
  • I am looking at API documentation for `SchemaValidationResults` class and I don't see the `Errors` property. I can see `NestedResults` property, which is a list `SchemaValidationResults`, which I can traverse and read `ErrorMessage`. Is this what you propose? https://gregsdennis.github.io/Manatee.Json/api/Manatee.Json.Schema.SchemaValidationResults.html – GKalnytskyi Jul 15 '20 at 06:45
  • Yes, in the object model, it's `NestedResults`. When serialized, this is transformed to either `errors` or `annotations` depending on the valid state. Sorry for the confusion. – gregsdennis Jul 22 '20 at 20:47
0

For my case I get the validation error list the following way.

public static List<string> GetValidationErrors(SchemaValidationResults validationResult)
{
    if (validationResult.IsValid)
    {
        return new List<string>(0);
    }

    var errorList = new List<string>(8);
    if (!string.IsNullOrWhiteSpace(validationResult.ErrorMessage))
    {
        errorList.Add(validationResult.ErrorMessage);
    }

    foreach (SchemaValidationResults vrslt in validationResult.NestedResults)
    {
        errorList.AddRange(GetValidationErrors(vrslt));
    }
    return errorList;
}
GKalnytskyi
  • 579
  • 7
  • 16