C# JSON Schema validation

Introduction

In this C# tutorial we will learn how to validate JSON objects against a JSON schema. We will be using the NJsonSchema package, which can be easily installed from the Visual Studio NuGet Package Manager, as shown in figure 1:

Installing the NJsonSchema package from the Visual Studio Package Manager.
Figure 1 – Installing the NJsonSchema package from the Visual Studio Package Manager.

This tutorial was tested with .NET Core v3.1 and with NJsonSchema v10.2.2.

The code

We will start by stating the namespaces used. We will need the NJsonSchema namespace, from the package mentioned in the introductory section, to perform the JSON schema validation.

using NJsonSchema;

We will also need the System namespace, to be able to access the Console to print the results of our program, and the System.Threading.Tasks namespace to be able to run some asynchronous code.

using System;
using System.Threading.Tasks;

As mentioned before, we will run some asynchronous code. So, our main code will be async and return a Task.

static async Task Main()
{
    // Main code
}

We will then start by defining a variable containing a JSON schema definition for a very simple object representing a person, with the following properties:

  • name (a string);
  • age (a number);
  • isMarried (a boolean)
var jsonSchema = @"
{
	""type"": ""object"",
	""properties"": {
		""name"": {
			""type"": ""string""
		},
		""age"": {
			""type"": ""integer"",
			""minimum"": 0
		},
		""isMarried"": {
			""type"": ""boolean""
		}
	}
}
";

Then we will define two JSON strings: one containing an object that is valid accordingly to the previous JSON schema, and another that is invalid.

var jsonDataValid = @"
{
	""name"": ""Jay"",
	""age"": 20,
	""isMarried"": true
}
";

var jsonDataInvalid = @"
{
	""name"": ""Jay"",
	""age"": ""20"",
	""isMarried"": ""true""
}
";

Now that we have our three JSONs, we will start by getting an object of class JsonSchema from our JSON schema string. To do so, we simply need to call the FromJsonAsync static method from the JsonSchema class, passing as input the string with the schema.

As output, the FromJsonAsync method returns a JsonSchema object that we can later use to perform the object validation. Note that this method is asynchronous, so we will use the await operator to wait for the operation to complete.

var schema = await JsonSchema.FromJsonAsync(jsonSchema);

To perform the validation of a JSON string accordingly to the previously obtained schema, we simply need to call the Validate method on our JsonSchema object, passing as input the string. As output, this method returns a list of objects of class ValidationError, representing each error found. If no error is found, the list will be empty.

We will apply the validation to both our JSON objects: the valid and the invalid.

var errorsForValidJson = schema.Validate(jsonDataValid);
var errorsForInvalidJson = schema.Validate(jsonDataInvalid);

After this, we will just iterate through both lists of errors and print them to the console. Note that we expect the first list to be empty (the object is valid) and only to find errors in the second. Note that the ValidationError class overrides the ToString method (as can be seen here), meaning that we can print the objects directly to the console.

Console.WriteLine("valid errors:");
foreach (var error in errorsForValidJson) Console.WriteLine(error);

Console.WriteLine("invalid errors:");
foreach (var error in errorsForInvalidJson) Console.WriteLine(error);

The complete code can be seen below.

namespace MessagePack
{
    using NJsonSchema;
    using System;
    using System.Threading.Tasks;

    class Program
    {
        static async Task Main()
        {

            var jsonSchema = @"
                {
                    ""type"": ""object"",
                    ""properties"": {
                        ""name"": {
                            ""type"": ""string""
                        },
                        ""age"": {
                            ""type"": ""integer"",
                            ""minimum"": 0
                        },
	                    ""isMarried"": {
                            ""type"": ""boolean""
                        }
                    }
                 }
            ";

            var jsonDataValid = @"
                {
                    ""name"": ""Jay"",
                    ""age"": 20,
                    ""isMarried"": true
                }
            ";

            var jsonDataInvalid = @"
                {
                    ""name"": ""Jay"",
                    ""age"": ""20"",
                    ""isMarried"": ""true""
                }
            ";

            var schema = await JsonSchema.FromJsonAsync(jsonSchema);

            var errorsForValidJson = schema.Validate(jsonDataValid);
            var errorsForInvalidJson = schema.Validate(jsonDataInvalid);

            Console.WriteLine("valid errors:");
            foreach (var error in errorsForValidJson) Console.WriteLine(error);

            Console.WriteLine("invalid errors:");
            foreach (var error in errorsForInvalidJson) Console.WriteLine(error);

        }
    }
}

Testing the code

To test the previous code, simply compile it and run it using a tool of your choice. I’m using Visual Studio 2019.

Upon running the code, you should get a result similar to figure 2. As can be seen, for the first object, we get no errors. For the second object, we get two errors: the first one indicates that age should be an Integer and the second that isMarried should be a Boolean.

Output of the program, showing the result of the JSON schema validation.
Figure 2 – Output of the program, showing the result of the JSON schema validation.

Related C# tutorials

Leave a Reply

%d bloggers like this: