How to Validate JSON in C# Effortlessly using JSON Schema file?

 There are situations where we may need to validate JSON data which we are receiving from external sources. This is done to ensure data integrity. This can be done easily with the help of a JSON Schema file which lists down the constraints and the template of JSON data.

Validating JSON using JSON Schema in C#

In this post we are going to see with an example, How we can validate the JSON data against the JSON Schema we are using. For this I have created a JSON Schema which lays down the template for the JSON data along with the constraints for the properties of JSON data. Next is to create the JSON data, for this demo, I have hardcoded the JSON data as a string.

Below code demonstrates these in action:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using System;
using System.Collections.Generic;

namespace JSONGeneratorFromSchema
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string schema = @"
{
    ""type"": ""object"",
  ""properties"": 
{
                ""countries"": {
                    ""type"": ""array"",
      ""items"": {
                        ""type"": ""string""
      }
                },
    ""address"": {
                    ""type"": ""object"",
      ""properties"": {
                    ""HouseNo"":{
                            ""type"":""number"",
                            ""default"" : 100
                    },
                    ""Street"":{
                            ""type"":""string"",
                            ""default"" : """"
                    },
                    ""city"":{
                            ""type"":""string"",
                            ""default"" : """"
                    },
                    ""Country"":{
                            ""type"":""string"",
                            ""default"" : """"
                    }
                  }
               }
            },
        }";
            var parsedSchema = JSchema.Parse(schema);

            var jsonData = @"
            {
                ""countries"" : [""Germany"",""USA"",""India""],
                ""address"" : {
                    ""HouseNo"" : 103,
                    ""Street"" : ""Street A"",
                    ""city"" : ""CityA"",
                    ""Country"" : ""CountryA""
                }
            }
";
            JObject jObj = JObject.Parse(jsonData);
            if(!jObj.IsValid(parsedSchema,out IList<ValidationError> errorMessages))
            {
                foreach (var error in errorMessages)
                {
                    Console.WriteLine($"{error.Message} : {error.Path}");
                }
            }
            Console.ReadLine();
        }
    }
}

As we can see from the above code I have used IsValid Extension API of JObject to validate the JSON Object against the schema. In the above code JSON data is valid as it satisfies all the constrains laid out by the JSON Schema.

For catching any error occurred during the validation phase we can supply a second argument to the IsValid API as an out param which captures the Validation Errors. In this example I have printed the Validation Error Message and the JSON Path where the error has occurred.

To demonstrate the validation error I changed the HouseNo from number to string as shown in the below code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
 var jsonData = @"
            {
                ""countries"" : [""Germany"",""USA"",""India""],
                ""address"" : {
                    ""HouseNo"" : ""103"",
                    ""Street"" : ""Street A"",
                    ""city"" : ""CityA"",
                    ""Country"" : ""CountryA""
                }
            }

After making this change if we try to run the application it will throw Validation error in the console as shown in the figure below:

JSON Validation Error Message

As seen from the above output we will be able to see the Validation error message and the exact path where the error has occurred.



Conclusion

Validation is a powerful tool to ensure the Data Integrity. JSON being the widely used data format in many applications, Validation against JSON Schema acts as a Safety net.  Troubleshooting Validation issues is also straight-forward with the support provided by the Validation API.



Comments

Popular posts from this blog

Creating RESTful Minimal WebAPI in .Net 6 in an Easy Manner! | FastEndpoints

Mastering Concurrency with Latches and Barriers in C++20: A Practical Guide for Students

Graph Visualization using MSAGL with Examples