JsonSchemaGenerator
Generates a JsonSchema4 object for a given type.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NJsonSchema.Annotations;
using NJsonSchema.Converters;
using NJsonSchema.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace NJsonSchema.Generation
{
public class JsonSchemaGenerator
{
public JsonSchemaGeneratorSettings Settings { get; }
public JsonSchemaGenerator(JsonSchemaGeneratorSettings settings)
{
Settings = settings;
}
public JsonSchema4 Generate(Type type, ISchemaResolver schemaResolver)
{
return Generate<JsonSchema4>(type, null, null, new JsonSchemaDefinitionAppender(Settings.TypeNameGenerator), schemaResolver);
}
public JsonSchema4 Generate(Type type, JsonSchema4 rootSchema, IEnumerable<Attribute> parentAttributes, ISchemaDefinitionAppender schemaDefinitionAppender, ISchemaResolver schemaResolver)
{
return Generate<JsonSchema4>(type, rootSchema, parentAttributes, schemaDefinitionAppender, schemaResolver);
}
public TSchemaType Generate<TSchemaType>(Type type, JsonSchema4 rootSchema, IEnumerable<Attribute> parentAttributes, ISchemaDefinitionAppender schemaDefinitionAppender, ISchemaResolver schemaResolver) where TSchemaType : JsonSchema4, new
{
TSchemaType val = HandleSpecialTypes<TSchemaType>(type);
if (val != null)
return val;
val = new TSchemaType();
if (rootSchema == null)
rootSchema = val;
JsonObjectTypeDescription jsonObjectTypeDescription = JsonObjectTypeDescription.FromType(type, parentAttributes, Settings.DefaultEnumHandling);
jsonObjectTypeDescription.ApplyType(val);
ApplyExtensionDataAttributes(val, type, parentAttributes);
if (val.Type.HasFlag(JsonObjectType.Object)) {
if (jsonObjectTypeDescription.IsDictionary)
GenerateDictionary(type, rootSchema, val, schemaDefinitionAppender, schemaResolver);
else {
val.TypeNameRaw = GetTypeName(type);
if (schemaResolver.HasSchema(type, false)) {
val.SchemaReference = schemaResolver.GetSchema(type, false);
return val;
}
if ((object)val.GetType() != typeof(JsonSchema4)) {
val.SchemaReference = Generate(type, rootSchema, parentAttributes, schemaDefinitionAppender, schemaResolver);
return val;
}
val.Description = GetDescription(type.GetTypeInfo(), type.GetTypeInfo().GetCustomAttributes());
GenerateObject(type, val, rootSchema, schemaDefinitionAppender, schemaResolver);
}
} else if (type.GetTypeInfo().get_IsEnum()) {
bool isIntegerEnumeration = jsonObjectTypeDescription.Type == JsonObjectType.Integer;
if (schemaResolver.HasSchema(type, isIntegerEnumeration)) {
val.Type = jsonObjectTypeDescription.Type;
val.SchemaReference = schemaResolver.GetSchema(type, isIntegerEnumeration);
return val;
}
if ((object)val.GetType() != typeof(JsonSchema4)) {
val.SchemaReference = Generate(type, rootSchema, parentAttributes, schemaDefinitionAppender, schemaResolver);
return val;
}
LoadEnumerations(type, val, jsonObjectTypeDescription);
val.TypeNameRaw = GetTypeName(type);
val.Description = type.GetXmlDocumentation();
schemaResolver.AddSchema(type, isIntegerEnumeration, val);
} 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) {
JsonSchemaAttribute customAttribute = type.GetTypeInfo().GetCustomAttribute<JsonSchemaAttribute>();
if ((object)customAttribute?.ArrayItem != null)
val.Item = Generate(customAttribute.ArrayItem, rootSchema, null, schemaDefinitionAppender, schemaResolver);
else
val.Item = JsonSchema4.CreateAnySchema();
} else
val.Item = Generate(type2, rootSchema, null, schemaDefinitionAppender, schemaResolver);
}
return val;
}
private static void ApplyExtensionDataAttributes<TSchemaType>(TSchemaType schema, Type type, IEnumerable<Attribute> parentAttributes) where TSchemaType : JsonSchema4, new
{
if (parentAttributes == null) {
JsonSchemaExtensionDataAttribute[] source = type.GetTypeInfo().GetCustomAttributes<JsonSchemaExtensionDataAttribute>().ToArray();
if (source.Any())
schema.ExtensionData = source.ToDictionary((JsonSchemaExtensionDataAttribute a) => a.Property, (JsonSchemaExtensionDataAttribute a) => a.Value);
} else {
JsonSchemaExtensionDataAttribute[] source2 = parentAttributes.OfType<JsonSchemaExtensionDataAttribute>().ToArray();
if (source2.Any())
schema.ExtensionData = source2.ToDictionary((JsonSchemaExtensionDataAttribute a) => a.Property, (JsonSchemaExtensionDataAttribute a) => a.Value);
}
}
private TSchemaType HandleSpecialTypes<TSchemaType>(Type type) where TSchemaType : JsonSchema4, new
{
if ((object)type == typeof(JObject) || (object)type == typeof(JToken) || (object)type == typeof(object))
return JsonSchema4.CreateAnySchema<TSchemaType>();
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, JsonSchema4 rootSchema, TSchemaType schema, ISchemaDefinitionAppender schemaDefinitionAppender, 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];
if ((object)type2 == typeof(object))
schema.AdditionalPropertiesSchema = JsonSchema4.CreateAnySchema();
else
schema.AdditionalPropertiesSchema = Generate(type2, rootSchema, null, schemaDefinitionAppender, 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, JsonSchema4 rootSchema, ISchemaDefinitionAppender schemaDefinitionAppender, ISchemaResolver schemaResolver) where TSchemaType : JsonSchema4, new
{
schemaResolver.AddSchema(type, false, schema);
schema.AllowAdditionalProperties = false;
GeneratePropertiesAndInheritance(type, schema, rootSchema, schemaDefinitionAppender, schemaResolver);
if (Settings.GenerateKnownTypes)
GenerateKnownTypes(type, rootSchema, schemaDefinitionAppender, schemaResolver);
}
private void GeneratePropertiesAndInheritance(Type type, JsonSchema4 schema, JsonSchema4 rootSchema, ISchemaDefinitionAppender schemaDefinitionAppender, ISchemaResolver schemaResolver)
{
string[] properties = GetTypeProperties(type);
foreach (PropertyInfo item in type.GetTypeInfo().DeclaredProperties.Where(delegate(PropertyInfo p) {
if (properties != null)
return properties.Contains(p.Name);
return true;
})) {
LoadProperty(type, item, schema, rootSchema, schemaDefinitionAppender, schemaResolver);
}
GenerateInheritance(type, schema, rootSchema, schemaDefinitionAppender, schemaResolver);
}
private void GenerateKnownTypes(Type type, JsonSchema4 rootSchema, ISchemaDefinitionAppender schemaDefinitionAppender, ISchemaResolver schemaResolver)
{
foreach (dynamic item in from a in type.GetTypeInfo().GetCustomAttributes()
where a.GetType().get_Name() == "KnownTypeAttribute"
select a) {
dynamic val = JsonObjectTypeDescription.FromType(item.Type, null, Settings.DefaultEnumHandling);
dynamic val2 = val.Type == JsonObjectType.Integer;
if ((!schemaResolver.HasSchema(item.Type, val2))) {
dynamic val3 = this.Generate(item.Type, rootSchema, null, schemaDefinitionAppender, schemaResolver);
schemaDefinitionAppender.Append(rootSchema, val3.ActualSchema);
}
}
}
private void GenerateInheritance(Type type, JsonSchema4 schema, JsonSchema4 rootSchema, ISchemaDefinitionAppender schemaDefinitionAppender, ISchemaResolver schemaResolver)
{
GenerateInheritanceDiscriminator(type, schema);
Type baseType = type.GetTypeInfo().get_BaseType();
if ((object)baseType != null && (object)baseType != typeof(object)) {
if (Settings.FlattenInheritanceHierarchy)
GeneratePropertiesAndInheritance(baseType, schema, rootSchema, schemaDefinitionAppender, schemaResolver);
else {
JsonSchema4 item = Generate(baseType, rootSchema, null, schemaDefinitionAppender, schemaResolver);
schema.AllOf.Add(item);
}
}
}
private void GenerateInheritanceDiscriminator(Type type, JsonSchema4 schema)
{
if (!Settings.FlattenInheritanceHierarchy) {
string text = TryGetInheritanceDiscriminator(CustomAttributeExtensions.GetCustomAttributes(type.GetTypeInfo(), false).OfType<Attribute>());
if (!string.IsNullOrEmpty(text)) {
if (schema.Properties.ContainsKey(text))
throw new InvalidOperationException("The JSON property '" + text + "' is defined multiple times on type '" + type.FullName + "'.");
schema.Discriminator = text;
schema.Properties[text] = new JsonProperty {
Type = JsonObjectType.String,
IsRequired = true
};
}
}
}
private string TryGetInheritanceDiscriminator(IEnumerable<Attribute> typeAttributes)
{
dynamic val = (typeAttributes != null) ? typeAttributes.FirstOrDefault((Attribute a) => a.GetType().get_Name() == "JsonConverterAttribute") : null;
if ((val != null) && ((Type)val.ConverterType).get_Name() == "JsonInheritanceConverter") {
dynamic val2 = val.ConverterParameters != null;
if ((val2 ? false : true) ? val2 : (val2 & (val.ConverterParameters.Length > 0)))
return (string)val.ConverterParameters[0];
return JsonInheritanceConverter.DefaultDiscriminatorName;
}
return null;
}
protected virtual string[] GetTypeProperties(Type type)
{
if ((object)type == typeof(Exception))
return new string[4] {
"InnerException",
"Message",
"Source",
"StackTrace"
};
return null;
}
private void LoadEnumerations(Type type, JsonSchema4 schema, JsonObjectTypeDescription typeDescription)
{
schema.Type = typeDescription.Type;
schema.Enumeration.Clear();
schema.EnumerationNames.Clear();
string[] names = Enum.GetNames(type);
foreach (string text in names) {
if (typeDescription.Type == JsonObjectType.Integer) {
object item = Convert.ChangeType(Enum.Parse(type, text), Enum.GetUnderlyingType(type));
schema.Enumeration.Add(item);
} else {
IEnumerable<Attribute> customAttributes = type.GetTypeInfo().GetDeclaredField(text).GetCustomAttributes();
dynamic val = TryGetAttribute(customAttributes, "System.Runtime.Serialization.EnumMemberAttribute");
dynamic val2 = val != null;
if ((val2 ? false : true) ? val2 : (val2 & !string.IsNullOrEmpty(val.Value)))
schema.Enumeration.Add((string)val.Value);
else
schema.Enumeration.Add(text);
}
schema.EnumerationNames.Add(text);
}
}
private void LoadProperty(Type parentType, PropertyInfo property, JsonSchema4 parentSchema, JsonSchema4 rootSchema, ISchemaDefinitionAppender schemaDefinitionAppender, ISchemaResolver schemaResolver)
{
Type type = property.PropertyType;
JsonObjectTypeDescription jsonObjectTypeDescription = JsonObjectTypeDescription.FromType(type, property.GetCustomAttributes(), Settings.DefaultEnumHandling);
Attribute[] array = property.GetCustomAttributes().ToArray();
if (!IsPropertyIgnored(parentType, array)) {
if (type.get_Name() == "Nullable`1")
type = type.GenericTypeArguments[0];
bool flag = !jsonObjectTypeDescription.IsDictionary && (jsonObjectTypeDescription.Type.HasFlag(JsonObjectType.Object) || jsonObjectTypeDescription.IsEnum);
JsonProperty jsonProperty;
if (flag) {
JsonSchema4 jsonSchema = Generate(type, rootSchema, property.GetCustomAttributes(), schemaDefinitionAppender, schemaResolver);
if (Settings.NullHandling == NullHandling.JsonSchema) {
jsonProperty = new JsonProperty();
jsonProperty.OneOf.Add(new JsonSchema4 {
SchemaReference = jsonSchema.ActualSchema
});
} else
jsonProperty = new JsonProperty {
SchemaReference = jsonSchema.ActualSchema
};
} else {
jsonProperty = Generate<JsonProperty>(type, rootSchema, property.GetCustomAttributes(), schemaDefinitionAppender, schemaResolver);
jsonObjectTypeDescription.ApplyType(jsonProperty);
}
string propertyName = JsonPathUtilities.GetPropertyName(property, Settings.DefaultPropertyNameHandling);
if (parentSchema.Properties.ContainsKey(propertyName))
throw new InvalidOperationException("The JSON property '" + propertyName + "' is defined multiple times on type '" + parentType.FullName + "'.");
parentSchema.Properties.Add(propertyName, jsonProperty);
Attribute attribute = TryGetAttribute(array, "System.ComponentModel.DataAnnotations.RequiredAttribute");
JsonPropertyAttribute customAttribute = property.GetCustomAttribute<JsonPropertyAttribute>();
bool flag2 = customAttribute != null && (customAttribute.Required == Required.Always || customAttribute.Required == Required.AllowNull);
bool num = attribute != null;
if (num | flag2)
parentSchema.RequiredProperties.Add(propertyName);
bool flag3 = customAttribute != null && customAttribute.Required == Required.AllowNull;
if (!num && (jsonObjectTypeDescription.IsNullable | flag3)) {
if (Settings.NullHandling == NullHandling.JsonSchema) {
if (flag)
jsonProperty.OneOf.Add(new JsonSchema4 {
Type = JsonObjectType.Null
});
else if (jsonProperty.Type == JsonObjectType.None) {
jsonProperty.OneOf.Add(new JsonSchema4 {
Type = JsonObjectType.None
});
jsonProperty.OneOf.Add(new JsonSchema4 {
Type = JsonObjectType.Null
});
} else {
jsonProperty.Type |= JsonObjectType.Null;
}
}
} else if (Settings.NullHandling == NullHandling.Swagger && !parentSchema.RequiredProperties.Contains(propertyName)) {
parentSchema.RequiredProperties.Add(propertyName);
}
dynamic val = TryGetAttribute(array, "System.ComponentModel.ReadOnlyAttribute");
if (val != null)
jsonProperty.IsReadOnly = ((byte)val.IsReadOnly != 0);
jsonProperty.Description = GetDescription(property, array);
ApplyPropertyAnnotations(jsonProperty, parentType, array, jsonObjectTypeDescription);
}
}
private static bool IsPropertyIgnored(Type parentType, Attribute[] propertyAttributes)
{
if (propertyAttributes.Any((Attribute a) => a is JsonIgnoreAttribute))
return true;
if (parentType.GetTypeInfo().GetCustomAttributes().Any((Attribute a) => a.GetType().get_Name() == "DataContractAttribute") && propertyAttributes.All((Attribute a) => a.GetType().get_Name() != "DataMemberAttribute") && !propertyAttributes.Any((Attribute a) => a is JsonPropertyAttribute))
return true;
return false;
}
public void ApplyPropertyAnnotations(JsonSchema4 jsonProperty, Type parentType, IList<Attribute> attributes, JsonObjectTypeDescription propertyTypeDescription)
{
dynamic val = TryGetAttribute(attributes, "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(attributes, "System.ComponentModel.DefaultValueAttribute");
val2 = (val3 != null);
if ((val2 ? false : true) ? val2 : (val2 & (val3.Value != null)))
jsonProperty.Default = (object)this.ConvertDefaultValue(parentType, attributes, val3);
dynamic val4 = TryGetAttribute(attributes, "System.ComponentModel.DataAnnotations.RegularExpressionAttribute");
if (val4 != null)
jsonProperty.Pattern = (string)val4.Pattern;
if (propertyTypeDescription.Type == JsonObjectType.Number || propertyTypeDescription.Type == JsonObjectType.Integer) {
dynamic val5 = TryGetAttribute(attributes, "System.ComponentModel.DataAnnotations.RangeAttribute");
if (val5 != null) {
if (val5.Minimum != null)
jsonProperty.Minimum = (double?)val5.Minimum;
if (val5.Maximum != null)
jsonProperty.Maximum = (double?)val5.Maximum;
}
MultipleOfAttribute multipleOfAttribute = attributes.OfType<MultipleOfAttribute>().SingleOrDefault();
if (multipleOfAttribute != null)
jsonProperty.MultipleOf = multipleOfAttribute.MultipleOf;
}
dynamic val6 = TryGetAttribute(attributes, "System.ComponentModel.DataAnnotations.MinLengthAttribute");
val2 = (val6 != null);
if ((val2 ? false : true) ? val2 : (val2 & (val6.Length != null))) {
if (propertyTypeDescription.Type == JsonObjectType.String)
jsonProperty.MinLength = (int?)val6.Length;
else if (propertyTypeDescription.Type == JsonObjectType.Array) {
jsonProperty.MinItems = (int)val6.Length;
}
}
dynamic val7 = TryGetAttribute(attributes, "System.ComponentModel.DataAnnotations.MaxLengthAttribute");
val2 = (val7 != null);
if ((val2 ? false : true) ? val2 : (val2 & (val7.Length != null))) {
if (propertyTypeDescription.Type == JsonObjectType.String)
jsonProperty.MaxLength = (int?)val7.Length;
else if (propertyTypeDescription.Type == JsonObjectType.Array) {
jsonProperty.MaxItems = (int)val7.Length;
}
}
}
private object ConvertDefaultValue(Type parentType, IEnumerable<Attribute> propertyAttributes, dynamic defaultValueAttribute)
{
if (((Type)defaultValueAttribute.Value.GetType()).GetTypeInfo().get_IsEnum()) {
if (JsonObjectTypeDescription.IsStringEnum(parentType, propertyAttributes, Settings.DefaultEnumHandling))
return defaultValueAttribute.Value.ToString();
return (int)defaultValueAttribute.Value;
}
return defaultValueAttribute.Value;
}
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);
}
}
}