Using Json.NET to generate JsonSchema

Actually generating the schema is pretty simple …

using Newtonsoft.Json.Schema;

var jsonSchemaGenerator = new JsonSchemaGenerator();
var myType = typeof(MyClass);
var schema = jsonSchemaGenerator.Generate(myType);
schema.Title = myType.Name; // this doesn't seem to get done within the generator

then write it to a file …

var writer = new StringWriter();
var jsonTextWriter = new JsonTextWriter(writer);
schema.WriteTo(jsonTextWriter);
dynamic parsedJson = JsonConvert.DeserializeObject(writer.ToString());
var prettyString = JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
var fileWriter = new StreamWriter("MySchema.txt");
fileWriter.WriteLine(schema.Title);
fileWriter.WriteLine(new string('-', schema.Title.Length));
fileWriter.WriteLine(prettyString);
fileWriter.Close();

What took me a while to figure out was that MyClass needs to be decorated with specific attributes in order for the schema to be correctly generated.

public class MyClass
{
    [JsonProperty(Required = Required.Always)]
    public string Forename { get; set; }

    [JsonProperty(Required = Required.Always)]
    public string Surname { get; set; }

    [JsonProperty(Required = Required.Always)]
    public string EmailAddress { get; set; }

    [JsonProperty(Required = Required.AllowNull)]
    public string MobilePhoneNumber { get; set; }
}

So, the JsonProperty attribute is your friend here! It took me a while to figure out, including some time stepping through the Json.NET source code in the debugger.

Advertisements

5 responses to “Using Json.NET to generate JsonSchema

  1. Thanks man, helped alot! OCD fiend in me had to point out code error in second block line 9, should be ‘fileWriter.Close();’ not ‘fileWrite.Close();’

    • I can’t remember! I checked my actual code and have since changed it to this …

      dynamic parsedJson = JsonConvert.DeserializeObject(writer.ToString());
      var prettyString = JsonConvert.SerializeObject(parsedJson, Formatting.Indented);

      … I’ve updated the content of the post to reflect this change.

  2. Pingback: Generate JSON Schema from C# class »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s