Validating JSON with JSON Schema in C#

Introduction

JSON Schema is a specification for validating structure-based, JSON-formatted data. JSON Schema is very similar to a grammar of some languages; it defines what data are permitted and which are not permitted. It’s a vocabulary that allows developers to annotate and validate JSON documents. It ensures the quality of submitted JSON data by a client. JSON Schema also describes existing data formats in human and machine readable documentation. The JSON Schema project is currently in draft 7.0 version and will be adopted by an IETF working group.

Json.NET Schema

VS Console application to validate JSON

using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JSONSchemaSample
{
   class Program
   {
      static void Main(string[] args)
      {
         string myschemaJson = @"{
            'description': 'An employee', 'type': 'object',
            'properties':
            {
               'name': {'type':'string'},
               'id': {'type':'string'},
               'company': {'type':'string'},
               'role': {'type':'string'},
               'skill': {'type': 'array',
               'items': {'type':'string'}
            }
         }";

         JsonSchema schema = JsonSchema.Parse(myschemaJson);

         JObject employee = JObject.Parse(@"{
            'name': 'Tapas', 'id': '12345', 'company': 'TCS',
            'role': 'developer',
            'skill': ['.NET', 'JavaScript', 'C#', 'Angular',
            'HTML']
         }");
         bool valid = employee.IsValid(schema);
         // True

         JsonSchema schema1 = JsonSchema.Parse(myschemaJson);

         JObject employee1 = JObject.Parse(@"{
            'name': null, 'id': '12345', 'company': 'TCS',
            'role': 'developer',
            'skill': ['.NET', 'JavaScript', 'C#', 'Angular',
            'HTML']
         }");

         IList<string> messages;
         bool valid1 = employee1.IsValid(schema1, out messages);
         // False
         // "Invalid type. Expected String but got Null. Line 2,
         // position 24."


         JsonSchema schema2 = new JsonSchema();
         schema2.Type = JsonSchemaType.Object;
         schema2.Properties = new Dictionary<string, JsonSchema>
         {
            { "name", new JsonSchema
               { Type = JsonSchemaType.String } },
            { "id", new JsonSchema
               { Type = JsonSchemaType.String } },
            { "company", new JsonSchema
               { Type = JsonSchemaType.String } },
            { "role", new JsonSchema
               { Type = JsonSchemaType.String } },
            {
               "skill", new JsonSchema
               {
                  Type = JsonSchemaType.Array,
                  Items = new List<JsonSchema>
                     { new JsonSchema
                        { Type = JsonSchemaType.String } }
               }
            },
         };

         JObject employee2 = JObject.Parse(@"{
            'name': 'Tapas', 'id': '12345',
            'company': 'TCS', 'role': 'developer',
            'skill': ['.NET', 'JavaScript', 'C#', 'Angular',
            'HTML']
         }");
         bool valid2 = employee2.IsValid(schema2);
         // True
      }
   }
}

JSON Schema is a standard which provides a coherent schema to validate a JSON “item.” Properties within the schema are also defined. For detailed implementation of JSON Schema, refer to the preceding link.

A true valid property signals that the JSON is valid. If the validation fails, it will be false and the errors property will contain an array of error messages. Refer to the following sample; it returns errors:

{
   errors: [
      {
         message: "Invalid type. Expected String but got Null.
                   Line 2, position 24.",
         property: "name"
      }
   ]
   valid: false
}

Conclusion

JSON Schema is still a draft version, but hopefully, we will get the production version soon. Most of the time, JSON validation is overlooked and the data is wrongly assumed to be correct. Now, we have the library to use for JSON validation. So, it’s up to you to use them. That’s all for today. Happy Coding!

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read