RicoSuter / NJsonSchema

JSON Schema reader, generator and validator for .NET
http://NJsonSchema.org
MIT License
1.38k stars 532 forks source link

Exclude a certain type from the inheritance hierarchy #1606

Open InspiringCode opened 1 year ago

InspiringCode commented 1 year ago

I have several inheritance hierarchies where I have a common base class that should not be included in the JSON inheritance hierarchy.

public class Entity<TEntity> {
    public Guid Id { get; }
}

// Lots of classes inheriting from Entity<T>, like `class Project : Entity<Project> { }`
public class ProjectCommand<T> where T : ICommand<T> {
    public Guid ProjectId { get; }
}

// Lots of classes inheriting from ProjectCommand<T>, like `class AddMember : ProjectCommand<AddMember> { }`

I know that there is the JsonSchemaFlattenAttribute that I could apply to all subclasses of Entity<T> but that are a lot of classes and it is easy to forget it on new subclasses. What I want is something like an [JsonSchemaFlatten(ExcludeFromHierarchy = true)] attribute that I could apply to Entity<T> or ProjectCommand<T> so that this class does not appear as EntityOfProject, EntityOfUser, etc. in my swagger.json.

I checked the source if I there is a hook or config option to achieve this, but I utterly failed. First idea was to check if I could override the ReflectionService to return the JsonSchemaFlattenAttribute for each direct subclass, but this is not possible since direct .NET reflection is used.

Second thing I tried is to somehow override the JsonSchemaGeneratorSettings.GetActualFlattenInheritanceHierarchy method which also failed since it is non-virtual (and would probably not work anyway because of settings cloning and so on).

Is there any way one could achieve this or could you add this feature to the next version of NSwag?