Json schema validation in .NET

 
 
  • Gérald Barré

It is often useful to validate JSON documents against a JSON schema. For example, you may want to validate the JSON document that you receive from a REST API or a configuration file written by a user. In this post, I describe how to validate JSON data against a JSON schema in .NET.

.NET doesn't support JSON schema validation out of the box. However, there are several third-party libraries that you can use to validate JSON data against a JSON schema. In this post, I use the JsonSchema.Net library (GitHub).

Let's create the project:

Shell
dotnet new console
dotnet add package JsonSchema.Net

The following code snippet shows how to validate 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!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub