This project provides a simple way to validate JSON objects in dotnet. The main use for the tool is in integration tests where you would — ideally — validate an API JSON response manually instead of using the model classes.
| Package | Nuget | Description |
|---|---|---|
| JsonValidator | Base package containing the validation logic | |
| JsonValidator.Shouldly | Extensions for Shouldly | |
| JsonValidator.FluentAssertions | Extensions for FluentAssertions |
- Parse the JSON string to a
System.Text.Json.JsonDocument - Define the object with the properties you would like to validate. This can be a regular class or an anonymous class as well. We recommend anonymous classes.
- Call the
ValidateMatchextension method on theJsonDocument. - The
ValidateMatchwill throw aValidationFailedExceptionif any value of the above defined object is not present or does not match the value in theJsonDocument. - Values that are present in the
JsonDocumentbut are not defined in the validation object are ignored. They will not influence the validation result.
JsonDocument.Parse(
"""
{
"name": "Anna Smith",
"title": null,
"level": 2,
"isAvailable": true,
"score": 4.5326,
"capabilities": ["accounting", "marketing", "sales"],
"personalData":
{
"age": 29,
"nickname": "Anny",
"isMarried": false
}
}
""")
.ValidateMatch(
new
{
name = "Anna Smith",
title = null as string,
level = 2,
isAvailable = true,
score = 4.5326,
capabilities = new[] { "accounting", "marketing", "sales" },
personalData = new
{
age = 29,
nickname = "Anny",
isMarried = false,
}
});