Skip to content

Consider making enum serialisation consistent with Spring #1101

@martin-walsh

Description

@martin-walsh

Is your feature request related to a problem? Please describe.

  • Rendering of enums (using Jackson) is implemented differently in spring and swagger-core.
  • Spring respects @JsonValuewhile swagger-core does not.

Describe the solution you'd like

  • Add out of the box PropertyCustomizer to make rendering consistent.

Example

    public PropertyCustomizer enumValuePropertyCustomizer() {
        return (property, type) -> {

            var javaType = (JavaType) type.getType();

            if (javaType.isEnumType()) {
                var rawClass = javaType.getRawClass();

                // Json.mapper() is the underlying jackson ObjectMapper singleton used by swagger-core
                var beanDesc = Json.mapper().getSerializationConfig().introspect(javaType);

                // Same implementation as Spring.
                var accessor = beanDesc.findJsonValueAccessor();

                if (accessor == null) {
                    return property;
                }

                if (property instanceof StringSchema) {
                    var values = Arrays.stream(rawClass.getEnumConstants())
                        .map(accessor::getValue)
                        .map(Object::toString)
                        .collect(Collectors.toList());

                    // Replace rather than add to the values, including discarding allowableValues option, as Enums will not allow any other content anyway in either request or response
                    property.setEnum(values);
                }
            }

            return property;
        };
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions