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(); } } } |
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:
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.
Comments
Post a Comment