OpenApiDiscriminator
Describes a schema discriminator.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NJsonSchema.References;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace NJsonSchema
{
public class OpenApiDiscriminator
{
private class DiscriminatorMappingConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return true;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
Dictionary<string, string> dictionary = serializer.Deserialize<Dictionary<string, string>>(reader);
if (dictionary != null && existingValue != null) {
IDictionary<string, JsonSchema> dictionary2 = (IDictionary<string, JsonSchema>)existingValue;
dictionary2.Clear();
{
foreach (KeyValuePair<string, string> item in dictionary) {
JsonSchema jsonSchema = new JsonSchema();
((IJsonReferenceBase)jsonSchema).ReferencePath = item.Value;
dictionary2[item.Key] = jsonSchema;
}
return existingValue;
}
}
return existingValue;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
IDictionary<string, JsonSchema> dictionary = value as IDictionary<string, JsonSchema>;
if (dictionary != null) {
Dictionary<string, string> dictionary2 = new Dictionary<string, string>();
foreach (KeyValuePair<string, JsonSchema> item in dictionary) {
dictionary2[item.Key] = ((IJsonReferenceBase)item.Value).ReferencePath;
}
JObject jObject = JObject.FromObject(dictionary2, serializer);
writer.WriteToken(jObject.CreateReader());
} else
writer.WriteValue((string)null);
}
}
[JsonProperty("propertyName", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
public string PropertyName { get; set; }
[JsonProperty("mapping", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
[JsonConverter(typeof(DiscriminatorMappingConverter))]
public IDictionary<string, JsonSchema> Mapping { get; } = new Dictionary<string, JsonSchema>();
[JsonIgnore]
public object JsonInheritanceConverter { get; set; }
public void AddMapping(Type type, JsonSchema schema)
{
dynamic jsonInheritanceConverter = JsonInheritanceConverter;
object jsonInheritanceConverter2 = JsonInheritanceConverter;
if ((object)((jsonInheritanceConverter2 != null) ? jsonInheritanceConverter2.GetType().GetRuntimeMethod("GetDiscriminatorValue", new Type[1] {
typeof(Type)
}) : null) != null) {
dynamic val = jsonInheritanceConverter.GetDiscriminatorValue(type);
Mapping[val] = new JsonSchema {
Reference = schema.ActualSchema
};
} else
Mapping[type.get_Name()] = new JsonSchema {
Reference = schema.ActualSchema
};
}
}
}