Validating JSON documents against a JSON schema is useful in many scenarios, such as verifying data received from a REST API or validating a user-authored configuration file.
.NET doesn't support JSON schema validation out of the box. However, several third-party libraries are available for this purpose. This post uses the JsonSchema.Net library (GitHub).
Let's create the project:
Shell
dotnet new console
dotnet add package JsonSchema.Net
The following code snippet validates JSON data against a JSON schema:
C#
using System.Text.Json.Nodes;
using Json.Schema;
var schema = """
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.com/product.schema.json",
"title": "Product",
"description": "A product from Acme's catalog",
"type": "object",
"properties": {
"productName": {
"description": "Name of the product",
"type": "string"
},
"price": {
"description": "The price of the product",
"type": "number",
"exclusiveMinimum": 0
}
},
"required": [ "productName", "price" ]
}
""";
var invalidJson = """
{
"productName": "test",
"price": -1
}
""";
// Validate the JSON data against the JSON schema
var jsonSchema = JsonSchema.FromText(schema);
var result = jsonSchema.Evaluate(JsonNode.Parse(invalidJson));
if (!result.IsValid)
{
Console.WriteLine("Invalid document");
if (result.HasErrors)
{
foreach (var error in result.Errors)
{
Console.WriteLine(error.Key + ": " + error.Value);
}
}
}
Do you have a question or a suggestion about this post? Contact me!