JsonSchemaResolver
Manager which resolves types to schemas and appends missing schemas to the root object.
using NJsonSchema.Generation;
using System;
using System.Collections.Generic;
namespace NJsonSchema
{
public class JsonSchemaResolver
{
private readonly Dictionary<string, JsonSchema4> _mappings = new Dictionary<string, JsonSchema4>();
private readonly JsonSchemaGeneratorSettings _settings;
private JsonSchema4 RootSchema => (JsonSchema4)RootObject;
public object RootObject { get; }
public IEnumerable<JsonSchema4> Schemas => _mappings.Values;
public JsonSchemaResolver(object rootObject, JsonSchemaGeneratorSettings settings)
{
_settings = settings;
RootObject = rootObject;
}
public bool HasSchema(Type type, bool isIntegerEnumeration)
{
return _mappings.ContainsKey(GetKey(type, isIntegerEnumeration));
}
public JsonSchema4 GetSchema(Type type, bool isIntegerEnumeration)
{
return _mappings[GetKey(type, isIntegerEnumeration)];
}
public virtual void AddSchema(Type type, bool isIntegerEnumeration, JsonSchema4 schema)
{
if ((object)schema.GetType() != typeof(JsonSchema4))
throw new InvalidOperationException("Added schema is not a JsonSchema4 instance.");
if (schema != RootObject)
AppendSchema(schema, _settings.SchemaNameGenerator.Generate(type));
_mappings.Add(GetKey(type, isIntegerEnumeration), schema);
}
public virtual void AppendSchema(JsonSchema4 schema, string typeNameHint)
{
if (schema == null)
throw new ArgumentNullException("schema");
if (schema == RootObject)
throw new ArgumentException("The root schema cannot be appended.");
if (!RootSchema.Definitions.Values.Contains(schema)) {
string text = _settings.TypeNameGenerator.Generate(schema, typeNameHint, RootSchema.Definitions.Keys);
if (!string.IsNullOrEmpty(text) && !RootSchema.Definitions.ContainsKey(text))
RootSchema.Definitions[text] = schema;
else
RootSchema.Definitions["ref_" + Guid.NewGuid().ToString().Replace("-", "_")] = schema;
}
}
private string GetKey(Type type, bool isIntegerEnum)
{
return type.FullName + (isIntegerEnum ? ":Integer" : string.Empty);
}
}
}