Generating JSON schema from C# class

42,176

Solution 1

Another option which supports generating JSON Schema v4 is NJsonSchema:

var schema = JsonSchema.FromType<Person>();
var schemaJson = schema.ToJson();

The library can be installed via NuGet.

Update for NJsonSchema v9.4.3+:

using NJsonSchema;

var schema = await JsonSchema.FromTypeAsync<Person>();
var schemaJson = schema.ToJson();

Solution 2

JsonSchemaGenerator js = new JsonSchemaGenerator();
var schema = js.Generate(typeof(Person));
schema.Title = typeof(Person).Name;
using (StreamWriter fileWriter = File.CreateText(filePath))
{
      fileWriter.WriteLine(schema);
}

Solution 3

For those who land here from google searching for the reverse
(generate the C# class from JSON) - I use those fine online tools:

JSON:
http://json2csharp.com/
(Source: http://jsonclassgenerator.codeplex.com/)

XML:
http://xmltocsharp.azurewebsites.net/
(Source: https://github.com/msyoung/XmlToCSharp)

Solution 4

This is supported in Json.NET via the Newtonsoft.Json.Schema NuGet package. Instructions on how to use it can be found in the official documentation, but I've also included a simple example below.

JSchemaGenerator generator = new JSchemaGenerator();
JSchema schema = generator.Generate(typeof(Person));
Console.WriteLine(schema.ToString());
//{
//  "type": "object",
//  "properties": {
//    "Name": {
//      "type": [ "string", "null" ]
//    },
//    "Age": { "type": "integer" }
//  },
//  "required": [ "Name", "Age" ]
//}
Share:
42,176

Related videos on Youtube

Ravi Gupta
Author by

Ravi Gupta

Updated on July 09, 2022

Comments

  • Ravi Gupta
    Ravi Gupta almost 2 years

    Is there any way to programmatically generate a JSON schema from a C# class?

    Something which we can do manually using http://www.jsonschema.net/

    • Rob Sedgwick
      Rob Sedgwick almost 7 years
      Have a log at this: csharp2json.azurewebsites.net
    • codah
      codah over 3 years
      Nobody picked up that site doesn't generate schema from C#, but from JSON. And the previous comment's link is C# to JSON, not schema. This however is one way to do it online. dotnetfiddle.net/sjmS9Z
  • sandiejat
    sandiejat about 7 years
    From reverse jsonclassgenerator tool is great. Another simple option is to use Edit->Paste Special-> Paste JSON as Classes in Visual Studio. This creates a class too! Quite handy sometimes.
  • Stefan Steiger
    Stefan Steiger about 7 years
    @sandiejat: Nice to know. Wonder since which version of VS.
  • sandiejat
    sandiejat about 7 years
    Seems like 2012.2 RC brought it. And we were busy doing it difficult way! :) blogs.msdn.microsoft.com/webdev/2012/12/18/…
  • Mario Villanueva
    Mario Villanueva over 3 years
    It not free, it has 10 time for hours