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;
public virtual bool HasRootObject => _rootSchema != null;
public IEnumerable<JsonSchema4> Schemas => _mappings.Values;
public JsonSchemaResolver(JsonSchemaGeneratorSettings settings)
{
_settings = settings;
}
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 != _rootSchema)
AppendSchema(schema, _settings.SchemaNameGenerator.Generate(type));
_mappings.Add(GetKey(type, isIntegerEnumeration), schema);
}
public virtual void SetRootObject(object rootObject)
{
_rootSchema = (JsonSchema4)rootObject;
}
public virtual void AppendSchema(JsonSchema4 schema, string typeNameHint)
{
if (schema == null)
throw new ArgumentNullException("schema");
if (schema == _rootSchema)
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);
}
}
}