Inheritance + Swagger UI + Model Example help
See original GitHub issueHi,
When using Swagger UI I am unable to get the Example Value to properly generate an example that contains the derived classes in the example.
[JsonConverter(typeof(EntityCustomJsonConverter))]
[KnownType(typeof(CompanyRequestModel))]
[KnownType(typeof(PersonRequestModel))]
public abstract class PartyBaseRequestModel : BaseObjectRequestModel
{
public EntityEnums.Parties.Role[] Roles { get; set; }
}
This BaseEntityCustomJsonConverter<T> is used on a custom ModelBinding for my incoming request to determine (from the EntityType property we ask in our request) which Object to case the jObject too.
public sealed class EntityCustomJsonConverter : BaseEntityCustomJsonConverter<BaseObjectRequestModel>
{
private const string EntityTypeKey = "EntityType";
protected override BaseObjectRequestModel Create(Type objectType, JObject jsonObject)
{
if (!jsonObject.TryGetValue(EntityTypeKey, StringComparison.InvariantCultureIgnoreCase, out var entityType))
{
return default;
}
switch (entityType.ToString().ToLowerInvariant())
{
case EntityTypes.Parties.Person:
return jsonObject.ToObject<PersonRequestModel>();
case EntityTypes.Parties.Company:
return jsonObject.ToObject<CompanyRequestModel>();
default:
throw new NotSupportedException();
}
}
}
{
protected abstract T Create(Type objectType, JObject jsonObject);
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jsonObject = JObject.Load(reader);
var target = Create(objectType, jsonObject);
if (target != null)
{
serializer.Populate(jsonObject.CreateReader(), target);
}
return target;
}
public override bool CanConvert(Type objectType)
{
return typeof(T).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
}
}
Image of partial Model Example:
Swagger UI see’s my inherited class in the Model’s according:
What I would actually like to see in Swagger UI is this: (This image was taken from a YAML file created by me for another API that we will create, hence the different properties - What I like achieve does not change though)
Notice how “nodes” property contains an AnyOf with a list of models. How can I achieve this through code?
Issue Analytics
- State:
- Created 5 years ago
- Comments:16 (6 by maintainers)
Well, I feel a bit silly. I never changed my SchemaType to OpenApi 3.0 - Only this supports the anyOf keyword.
With this code:
and the settings:
I was able to achieve:
Thanks for support! 👍
Related PR: https://github.com/RSuter/NJsonSchema/pull/733