Validating JSON Against a Schema

November 21, 2023

JSON is a very forgiving format for transmitting information. It’s rigid in its structure, but there are no rules in terms of the content.

You can, however, implement a schema definition for it. In this post, I’ll talk about how to create such a schema and how to validate against it.

Throughout this post, I’ll be using this library - which provides the functionality that I’m speaking about.

Let’s start with generating the schema. There’s a number of ways to do this, but one is to create a C# class:

class MyClass
{
    [Required]
    public string Name { get; set; }

    [Required]
    public string Description { get; set; }

    public string TestField1 { get; set; }

    public int TestInt1 { get; set; }
}

You can validate against this, or just view it like this:

var schema = JsonSchema.FromType<MyClass>();
Console.WriteLine(schema.ToJson());

Here’s the Output:

Schema

You can save this schema and load it from a file, or generate your own file; for example:

var jsonSchema = await JsonSchema.FromFileAsync("JSON/schema.json");
var json = await File.ReadAllTextAsync(jsonFile);
var errors = jsonSchema.Validate(json);
foreach (var error in errors)
{
    Console.WriteLine(error);
}

If an error is present then the schema doesn’t match:

Schema Fail



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024