swagger-core icon indicating copy to clipboard operation
swagger-core copied to clipboard

Propagate JsonView annotation when resolving schema properties

Open gabrielhof opened this issue 1 year ago • 0 comments

I'm currently using Jackson's @JsonView annotation to include/exclude class properties based on the API operation that is being performed (e.g., create, update, read, etc.).

I have a specific need where I must annotate a class with @SchemaProperties, @SchemaProperty, and @Schema. However, the ModelResolver (Jackson-specific implementation of ModelConverter) ends up not propagating the @JsonView annotation when resolving the classes of the properties defined with @SchemaProperties. This causes the resulting schema to include properties that should be excluded for certain operations.

https://github.com/swagger-api/swagger-core/blob/e6d3fa3608d32d7c74fd62a007253f440a1f773d/modules/swagger-core/src/main/java/io/swagger/v3/core/jackson/ModelResolver.java#L881

https://github.com/swagger-api/swagger-core/blob/e6d3fa3608d32d7c74fd62a007253f440a1f773d/modules/swagger-core/src/main/java/io/swagger/v3/core/jackson/ModelResolver.java#L1775

Example

public class CommonViews {

    public static class Update { }

}

@PatchMapping("/update")
public void update(@JsonView(CommonViews.Update.class) AnnotatedWithSchemaProperties payload) {
    // logic
}

@SchemaProperties({
    @SchemaProperty(
        name = "my_custom_property",
        schema = @Schema(implementation = PropertyAnnotatedWithJsonView.class)
   )
})
public class AnnotatedWithSchemaProperties {
}

public class PropertyAnnotatedWithJsonView {

  private String alwaysIncludedProp;

  @JsonView(CommonViews.Update.class)
  private String includedOnlyWhenUpdating;

}

Alternative Solution

I was able to overcome the problem for now by defining a "dummy" setter method, causing the schema to be generated the way I'd expected:

@JsonProperty("my_custom_property")
public void setMyCustomProperty(PropertyAnnotatedWithJsonView myCustomProperty) {
    // logic
}

Additional Context

  • I'm using Swagger Core via Springdoc (which can be assumed based on the example above)
  • In case it is helpful, I'm using @SchemaProperties/@SchemaProperty/@Schema in a class that allows dynamic properties to be provided by consumers via the @JsonAnySetter/@JsonAnyGetter annotations. @SchemaProperties/... allow me to provide some examples in the generated schema to our consumers.

gabrielhof avatar Aug 20 '24 17:08 gabrielhof