dcsimg

WEBINAR:
On-Demand

Application Modernization: What Is It and How to Get Started


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

Newtonsoft provides a complete JSON Schema framework for .NET. They provide perpetual and royalty-free licenses for commercial use with easy to use and well-documented API in their Web site. You can protect your applications from invalid JSON by using Json.NET Schema by validating existing JSON. It can also generate JSON Schemas automatically from your existing .NET types. JSON Schema is tuned for high performance schema validation against a JSON document. Its unique streaming validation enables speed and efficiency.

As per Json.NET, it's twice as fast as the .NET Framework's XmlSchema when validating equivalent data.

.NET Application to Validate JSON with JSON Schema

Now, let's create an application to demonstrate JSON Schema validation. Open Visual Studio and select a new project and, from Visual C#, select "Console Application" and provide the name 'JSONSchemaSample', as shown in Figure 1. Click OK.

VS Console application to validate JSON
Figure 1: VS Console application to validate JSON

We will use Json.NET to validate JSON. The Json.NET library supports the JSON Schema standard via the JsonSchema and JsonValidatingReader classes. These classes are available under the Newtonsoft.Json.Schema namespace.

To install Newtonsoft.Json.Schema, right-click the solution created in the previous step and go to "Manage NuGet Packages." In the search bar, type "Newtonsoft.Json.Schema" and install the package that appears (see Figure 2).

Install JSON Schema NuGet Package
Figure 2: Install JSON Schema NuGet Package

Next, I have written the following code to create a JSON Schema and validate it. The simplest way to check if JSON is valid is by loading the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema. It returns a true/false value.

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!



About the Author

Tapas Pal

I am working in Microsoft Technology for last 15 years and presently working with Cognizant Technology Solutions, India as Senior Architect. I have completed TOGAF 9.1,Microsoft Certification on .NET 1.1 , .NET 2.0, SQL Server 2005 and Sharepoint. Please visit my Blog - http://tapas-pal.blogspot.com/

Related Articles

Comments

  • Good Article

    Posted by Subhajit Giri on 09/20/2018 06:57am

    This is a good helpful article .This is important for webapi input data validation.

    Reply
  • You must have javascript enabled in order to post comments.

Leave a Comment
  • Your email address will not be published. All fields are required.

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date