JsonSchemaGenerator
Generates a JsonSchema4 object for a given type.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NJsonSchema.Annotations;
using NJsonSchema.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace NJsonSchema
{
public class JsonSchemaGenerator
{
public JsonSchemaGeneratorSettings Settings { get; set; }
public JsonSchemaGenerator(JsonSchemaGeneratorSettings settings)
{
Settings = settings;
}
public JsonSchema4 Generate(Type type, ISchemaResolver schemaResolver)
{
return Generate<JsonSchema4>(type, schemaResolver);
}
public TSchemaType Generate<TSchemaType>(Type type, ISchemaResolver schemaResolver) where TSchemaType : JsonSchema4, new
{
return Generate<TSchemaType>(type, null, schemaResolver);
}
public TSchemaType Generate<TSchemaType>(Type type, IEnumerable<Attribute> parentAttributes, ISchemaResolver schemaResolver) where TSchemaType : JsonSchema4, new
{
TSchemaType val = HandleSpecialTypes<TSchemaType>(type);
if (val != null)
return val;
val = new TSchemaType();
JsonObjectTypeDescription jsonObjectTypeDescription = JsonObjectTypeDescription.FromType(type);
val.Type = jsonObjectTypeDescription.Type;
val.Format = jsonObjectTypeDescription.Format;
ApplyJsonSchemaAttribute(type, val);
if (val.Type.HasFlag(JsonObjectType.Object)) {
if (jsonObjectTypeDescription.IsDictionary)
GenerateDictionary(type, val, schemaResolver);
else {
val.TypeName = GetTypeName(type);
if (schemaResolver.HasSchema(type, false)) {
val.SchemaReference = schemaResolver.GetSchema(type, false);
return val;
}
val.Description = GetDescription(type.GetTypeInfo(), type.GetTypeInfo().GetCustomAttributes());
GenerateObject(type, val, schemaResolver);
}
} else if (val.Type.HasFlag(JsonObjectType.Array)) {
val.Type = JsonObjectType.Array;
Type[] genericTypeArguments = GetGenericTypeArguments(type);
Type type2 = (genericTypeArguments.Length == 0) ? type.GetElementType() : genericTypeArguments[0];
if ((object)type2 == null)
throw new InvalidOperationException("Could not find item type of array type '" + type.FullName + "'.");
val.Item = Generate<JsonSchema4>(type2, schemaResolver);
} else if (type.GetTypeInfo().get_IsEnum()) {
bool flag = IsIntegerEnumeration(parentAttributes) || HasStringEnumConverter(type.GetTypeInfo().GetCustomAttributes());
if (schemaResolver.HasSchema(type, flag)) {
val.Type = (flag ? JsonObjectType.Integer : JsonObjectType.String);
val.SchemaReference = schemaResolver.GetSchema(type, flag);
return val;
}
LoadEnumerations(type, val, flag, parentAttributes);
val.TypeName = GetTypeName(type);
schemaResolver.AddSchema(type, flag, val);
}
return val;
}
protected bool IsIntegerEnumeration(IEnumerable<Attribute> attributes)
{
JsonObjectType jsonObjectType = (Settings.DefaultEnumHandling == EnumHandling.String) ? JsonObjectType.String : JsonObjectType.Integer;
if (HasStringEnumConverter(attributes))
jsonObjectType = JsonObjectType.String;
return jsonObjectType == JsonObjectType.Integer;
}
private void ApplyJsonSchemaAttribute<TSchemaType>(Type type, TSchemaType schema) where TSchemaType : JsonSchema4, new
{
JsonSchemaAttribute customAttribute = type.GetTypeInfo().GetCustomAttribute<JsonSchemaAttribute>();
if (customAttribute != null) {
if (customAttribute.Type != 0)
schema.Type = customAttribute.Type;
if (!string.IsNullOrEmpty(customAttribute.Format))
schema.Format = customAttribute.Format;
}
}
private bool HasStringEnumConverter(IEnumerable<Attribute> attributes)
{
if (attributes == null)
return false;
dynamic val = (attributes != null) ? attributes.FirstOrDefault((Attribute a) => a.GetType().get_Name() == "JsonConverterAttribute") : null;
if ((val != null) && ((Type)val.ConverterType).get_Name() == "StringEnumConverter")
return true;
return false;
}
private TSchemaType HandleSpecialTypes<TSchemaType>(Type type) where TSchemaType : JsonSchema4, new
{
if ((object)type == typeof(object) || (object)type == typeof(JObject)) {
TSchemaType val = new TSchemaType();
val.Type = JsonObjectType.Object;
val.AllowAdditionalProperties = true;
return val;
}
if ((object)type == typeof(Type)) {
TSchemaType val2 = new TSchemaType();
val2.Type = JsonObjectType.String;
return val2;
}
return null;
}
private string GetTypeName(Type type)
{
if (type.IsConstructedGenericType)
return type.get_Name().Split(new char[1] {
'`'
}).First() + GetTypeName(type.GenericTypeArguments[0]);
return type.get_Name();
}
private void GenerateDictionary<TSchemaType>(Type type, TSchemaType schema, ISchemaResolver schemaResolver) where TSchemaType : JsonSchema4, new
{
Type[] genericTypeArguments = GetGenericTypeArguments(type);
if (genericTypeArguments.Length != 2)
throw new InvalidOperationException("Could not find value type of dictionary type '" + type.FullName + "'.");
Type type2 = genericTypeArguments[1];
schema.AdditionalPropertiesSchema = Generate<JsonProperty>(type2, schemaResolver);
schema.AllowAdditionalProperties = true;
}
public Type[] GetGenericTypeArguments(Type type)
{
Type[] genericTypeArguments = type.GenericTypeArguments;
while ((object)type != null && (object)type != typeof(object) && genericTypeArguments.Length == 0) {
type = type.GetTypeInfo().get_BaseType();
if ((object)type != null)
genericTypeArguments = type.GenericTypeArguments;
}
return genericTypeArguments;
}
protected virtual void GenerateObject<TSchemaType>(Type type, TSchemaType schema, ISchemaResolver schemaResolver) where TSchemaType : JsonSchema4, new
{
schemaResolver.AddSchema(type, false, schema);
schema.AllowAdditionalProperties = false;
GeneratePropertiesAndInheritance(type, schema, schemaResolver);
}
private void GeneratePropertiesAndInheritance<TSchemaType>(Type type, TSchemaType schema, ISchemaResolver schemaResolver) where TSchemaType : JsonSchema4, new
{
string[] properties = GetTypeProperties(type);
foreach (PropertyInfo item in type.GetTypeInfo().DeclaredProperties.Where(delegate(PropertyInfo p) {
if (properties != null)
return Enumerable.Contains<string>((IEnumerable<string>)properties, p.Name);
return true;
})) {
LoadProperty(item, schema, schemaResolver);
}
GenerateInheritance(type, schema, schemaResolver);
}
private void GenerateInheritance(Type type, JsonSchema4 schema, ISchemaResolver schemaResolver)
{
Type baseType = type.GetTypeInfo().get_BaseType();
if ((object)baseType != null && (object)baseType != typeof(object)) {
if (Settings.FlattenInheritanceHierarchy)
GeneratePropertiesAndInheritance(baseType, schema, schemaResolver);
else {
JsonProperty item = Generate<JsonProperty>(baseType, schemaResolver);
schema.AllOf.Add(item);
}
}
}
protected virtual string[] GetTypeProperties(Type type)
{
if ((object)type == typeof(Exception))
return new string[4] {
"InnerException",
"Message",
"Source",
"StackTrace"
};
return null;
}
private void LoadEnumerations<TSchemaType>(Type type, TSchemaType schema, bool isIntegerEnumeration, IEnumerable<Attribute> parentAttributes) where TSchemaType : JsonSchema4, new
{
if (isIntegerEnumeration) {
schema.Type = JsonObjectType.Integer;
schema.Enumeration.Clear();
schema.EnumerationNames.Clear();
string[] enumNames = GetEnumNames(type, parentAttributes);
foreach (string text in enumNames) {
object item = Convert.ChangeType(Enum.Parse(type, text), Enum.GetUnderlyingType(type));
schema.Enumeration.Add(item);
schema.EnumerationNames.Add(text);
}
} else {
schema.Type = JsonObjectType.String;
schema.Enumeration.Clear();
schema.EnumerationNames.Clear();
string[] enumNames = GetEnumNames(type, parentAttributes);
foreach (string item2 in enumNames) {
schema.Enumeration.Add((object)item2);
schema.EnumerationNames.Add(item2);
}
}
}
private string[] GetEnumNames(Type type, IEnumerable<Attribute> parentAttributes)
{
if (HasStringEnumConverter(type.GetTypeInfo().GetCustomAttributes()) || (parentAttributes != null && HasStringEnumConverter(parentAttributes)))
return Enum.GetNames(type).Select(delegate(string name) {
IEnumerable<Attribute> customAttributes = type.GetTypeInfo().GetDeclaredField(name).GetCustomAttributes();
object obj = TryGetAttribute(customAttributes, "System.Runtime.Serialization.EnumMemberAttribute");
if ((dynamic)obj != null)
return (string)((dynamic)obj).Value;
return name;
}).ToArray();
return Enum.GetNames(type);
}
private void LoadProperty<TSchemaType>(PropertyInfo property, TSchemaType parentSchema, ISchemaResolver schemaResolver) where TSchemaType : JsonSchema4, new
{
Type propertyType = property.PropertyType;
JsonObjectTypeDescription jsonObjectTypeDescription = JsonObjectTypeDescription.FromType(propertyType);
Attribute[] array = property.GetCustomAttributes().ToArray();
if (array.All((Attribute a) => !(a is JsonIgnoreAttribute))) {
JsonProperty jsonProperty = Generate<JsonProperty>(propertyType, property.GetCustomAttributes(), schemaResolver);
string propertyName = JsonPathUtilities.GetPropertyName(property);
parentSchema.Properties.Add(propertyName, jsonProperty);
Attribute attribute = TryGetAttribute(array, "System.ComponentModel.DataAnnotations.RequiredAttribute");
JsonPropertyAttribute customAttribute = property.GetCustomAttribute<JsonPropertyAttribute>();
bool flag = customAttribute != null && (customAttribute.Required == Required.Always || customAttribute.Required == Required.AllowNull);
bool num = attribute != null;
if (num | flag)
parentSchema.RequiredProperties.Add(propertyName);
bool flag2 = customAttribute != null && customAttribute.Required == Required.AllowNull;
bool flag3 = !jsonObjectTypeDescription.IsAlwaysRequired;
if (!num && (flag3 | flag2))
jsonProperty.Type |= JsonObjectType.Null;
dynamic val = TryGetAttribute(array, "System.ComponentModel.DataAnnotations.DisplayAttribute");
dynamic val2 = val != null;
if ((val2 ? false : true) ? val2 : (val2 & (val.Name != null)))
jsonProperty.Title = (string)val.Name;
dynamic val3 = TryGetAttribute(array, "System.ComponentModel.ReadOnlyAttribute");
if (val3 != null)
jsonProperty.IsReadOnly = ((byte)val3.IsReadOnly != 0);
dynamic val4 = TryGetAttribute(array, "System.ComponentModel.DefaultValueAttribute");
val2 = (val4 != null);
if ((val2 ? false : true) ? val2 : (val2 & (val4.Value != null)))
jsonProperty.Default = (object)val4.Value;
jsonProperty.Description = GetDescription(property, array);
dynamic val5 = TryGetAttribute(array, "System.ComponentModel.DataAnnotations.RegularExpressionAttribute");
if (val5 != null)
jsonProperty.Pattern = (string)val5.Pattern;
if (jsonObjectTypeDescription.Type == JsonObjectType.Number || jsonObjectTypeDescription.Type == JsonObjectType.Integer) {
dynamic val6 = TryGetAttribute(array, "System.ComponentModel.DataAnnotations.RangeAttribute");
if (val6 != null) {
if (val6.Minimum != null)
jsonProperty.Minimum = (double?)val6.Minimum;
if (val6.Maximum != null)
jsonProperty.Maximum = (double?)val6.Maximum;
}
}
dynamic val7 = TryGetAttribute(array, "System.ComponentModel.DataAnnotations.MinLengthAttribute");
val2 = (val7 != null);
if ((val2 ? false : true) ? val2 : (val2 & (val7.Length != null))) {
if (jsonObjectTypeDescription.Type == JsonObjectType.String)
jsonProperty.MinLength = (int?)val7.Length;
else if (jsonObjectTypeDescription.Type == JsonObjectType.Array) {
jsonProperty.MinItems = (int)val7.Length;
}
}
dynamic val8 = TryGetAttribute(array, "System.ComponentModel.DataAnnotations.MaxLengthAttribute");
val2 = (val8 != null);
if ((val2 ? false : true) ? val2 : (val2 & (val8.Length != null))) {
if (jsonObjectTypeDescription.Type == JsonObjectType.String)
jsonProperty.MaxLength = (int?)val8.Length;
else if (jsonObjectTypeDescription.Type == JsonObjectType.Array) {
jsonProperty.MaxItems = (int)val8.Length;
}
}
}
}
private string GetDescription(MemberInfo memberInfo, IEnumerable<Attribute> attributes)
{
dynamic val = TryGetAttribute(attributes, "System.ComponentModel.DescriptionAttribute");
dynamic val2 = val != null;
if ((val2 ? false : true) ? val2 : (val2 & (val.Description != null)))
return (string)val.Description;
dynamic val3 = TryGetAttribute(attributes, "System.ComponentModel.DataAnnotations.DisplayAttribute");
val2 = (val3 != null);
if ((val2 ? false : true) ? val2 : (val2 & (val3.Description != null)))
return (string)val3.Description;
string xmlDocumentation = memberInfo.GetXmlDocumentation();
if (xmlDocumentation != string.Empty)
return xmlDocumentation;
return null;
}
private Attribute TryGetAttribute(IEnumerable<Attribute> attributes, string attributeType)
{
return attributes.FirstOrDefault((Attribute a) => a.GetType().FullName == attributeType);
}
}
}