I am using JSON.NET to generate JSON Schema from c# object class. But I was unable to add any other json schema attributes e.g. maxLength, pattern(regex to validate email),
James Newton-King is right in his answer, I'll just expand it with a code example so people stumbling onto this page don't need to study the whole documentation.
So you can use the attributes provided with .NET to specify those addidional options, like maximum length of the string or allowed regex pattern. Here are some examples:
public class MyDataModel
{
public enum SampleEnum { EnumPosition1, EnumPosition2, EnumPosition3 }
[JsonProperty(Required = Required.Always)]
[RegularExpression(@"^[0-9]+$")]
public string PatternTest { get; set; }
[JsonProperty(Required = Required.Always)]
[MaxLength(3)]
public string MaxLength3 { get; set; }
[JsonProperty(Required = Required.AllowNull)]
[EnumDataType(typeof(SampleEnum))]
public string EnumProperty { get; set; }
}
The annotations above come from System.ComponentModel.DataAnnotations namespace.
To make those additional attributes affect resulting json schema, you need to use JSchemaGenerator class distributed with Json.NET Schema package. If you use older JsonSchemaGenerator, then some upgrade is needed, as it's now deprecated and does not contain new functions like the aforementioned.
Here's a sample function that generates Json Schema for the class above:
///
/// Generates JSON schema for a given C# class using Newtonsoft.Json.Schema library.
///
/// class type
/// a string containing JSON schema for a given class type
internal static string GenerateSchemaForClass(Type myType)
{
JSchemaGenerator jsonSchemaGenerator = new JSchemaGenerator();
JSchema schema = jsonSchemaGenerator.Generate(myType);
schema.Title = myType.Name;
return schema.ToString();
}
and you can use it just like this:
string schema = GenerateSchemaForClass(typeof(MyDataModel));