51

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/

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
Ravi Gupta
  • 6,258
  • 17
  • 56
  • 79
  • 2
    Have a log at this: http://csharp2json.azurewebsites.net/ – Rob Sedgwick May 12 '17 at 21:12
  • 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. https://dotnetfiddle.net/sjmS9Z – codah Oct 21 '20 at 00:46

4 Answers4

42

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();
Rico Suter
  • 11,548
  • 6
  • 67
  • 93
8

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" ]
//}
mark.monteiro
  • 2,609
  • 2
  • 33
  • 38
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);
}
Daniel
  • 984
  • 8
  • 14
1

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)

Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442
  • 2
    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. – sandiejat Mar 16 '17 at 05:25
  • @sandiejat: Nice to know. Wonder since which version of VS. – Stefan Steiger Mar 16 '17 at 19:17
  • Seems like 2012.2 RC brought it. And we were busy doing it difficult way! :) https://blogs.msdn.microsoft.com/webdev/2012/12/18/paste-json-as-classes-in-asp-net-and-web-tools-2012-2-rc/ – sandiejat Mar 16 '17 at 23:09