question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Inheritance + Swagger UI + Model Example help

See original GitHub issue

Hi,

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: image

Swagger UI see’s my inherited class in the Model’s according: image

image

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) image

Notice how “nodes” property contains an AnyOf with a list of models. How can I achieve this through code?

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:16 (6 by maintainers)

github_iconTop GitHub Comments

8reactions
wesley-pattisoncommented, Sep 8, 2018

Well, I feel a bit silly. I never changed my SchemaType to OpenApi 3.0 - Only this supports the anyOf keyword.

With this code:

            if (context.Type.Name is nameof(PartyBaseRequestModel) || context.Type.Name is nameof(BaseObjectRequestModel))
            {
                var attributes = context.Type.GetCustomAttributes(typeof(KnownTypeAttribute), true) as Attribute[];
                foreach (var attribute1 in attributes)
                {
                    var attribute = (KnownTypeAttribute) attribute1;
                    var schema = await context.Generator.GenerateWithReferenceAsync<JsonSchema4>(attribute.Type, attributes, context.Resolver,
                        async (p, s) => {});
                    context.Schema.AnyOf.Add(schema);
                }

                context.Schema.Properties.Clear();
                context.Schema.AllowAdditionalProperties = true;
            }

and the settings:

                settings.GeneratorSettings.FlattenInheritanceHierarchy = true;
                settings.GeneratorSettings.SchemaType = SchemaType.OpenApi3;
                settings.GeneratorSettings.SchemaProcessors.Add(new KnownTypeSchemaProcessor());

I was able to achieve: image

Thanks for support! 👍

2reactions
RicoSutercommented, Sep 6, 2018
Read more comments on GitHub >

github_iconTop Results From Across the Web

Inheritance and Polymorphism
OAS 3 This guide is for OpenAPI 3.0. Inheritance and Polymorphism. Model Composition. In your API, you may have model schemas that share...
Read more >
Swagger Inheritance and Composition
Composition is basically saying I have the properties of X and my own properties. . Inheritance suggests a relationship X is my parent....
Read more >
Make Swagger UI usable even with class inheritance ... - Wei He
In this article, I would like to share my “code first” experience with Swagger during implementing a REST API which data models have...
Read more >
Techniques - Type inheritance support in Swagger API
Problem. In this example, only the BaseObject will be exposed in Swagger. DerivedObject and AnotherDerivedObject will be missing from JSON with ...
Read more >
Example for using inheritance with swagger-springmvc
The initial setup worked fine and the web application generates the REST documentation. But currently we are facing problems, when using Java ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found