Generate JSON Schema from C# class

This text demonstrates how to generate JSON Schema for a given C# class. If you like strong-typed languages like C#, then you will probably love JSON Schema, as it allows to describe JSON structure in terms of data types, maximum length of strings, regex patterns for field validation etc. If you use Visual Studio 2013 Update 4 or newer, then you will also have full IntelliSense support for this standard, which makes writing JavaScript code much less error-prone and more fun.

This text is based on my StackOverflow answer and was inspired by Using Json.NET to generate JsonSchema article (although now this result can be achieved with much less code as you will see).

Generate JSON Schema based on C# class

What you need is a Json.NET Schema package. If your IDE supports NuGet Packages, and Visual Studio does for ages, this is the best way to add the library to your project.

Once you have downloaded the library, you can use the code like the one below to generate your schema:

This is how to use it with a class describing some data model:

string schema = GenerateSchemaForClass(typeof(MyDataModel));

Add annotations to your data

To make the attribute appear in schema, use JsonProperty annotation. If you want the schema to include additional attributes to restrict the data in some fields, you might use some of the data annotation attributes, some of which you might know if you worked with WCF, WebServices or similar. Full list of supported attributes is listed in Json Schema documentation. Here are some common ones:

I think that those are self-explaining. If you try to generate the schema and use it in JSON file, you will notice that Visual Studio will suggest property names based on the schema and show warnings when you provade invalid data (for example if the string in the second property is longer than 3 characters).

Json Schema: validation in Visual Studio 2015 RC

Json Schema: validation in Visual Studio 2015 RC