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

Jackson annotations ignored on enum class

Open swarth100 opened this issue 4 years ago • 1 comments

I have a dataclass that is used as a field in complex request and response bodies. The class uses JsonFormat to have custom serialisation:

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum User {
    FOO(1, "Bar");

    User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    private int id;
    private String name;
}

I would expect it to be serialised as:

"User" : {
    "properties" : {
        "id" : {
            "format" : "int32",
            "type" : "integer"
        },
        "name" : {
            "type" : "string"
        }
    },
    "type" : "object"
}

Unfortunately it gets serialised as:

"user" : {
    "enum" : [ "FOO" ],
    "type" : "string"
}

I have tried the workarounds listed in https://github.com/swagger-api/swagger-core/issues/2969, but it seems like most enum class-level Jackson annotations are currently ignored.

The only workaround I found was:

class UserSer {
    @JsonProperty
    private int id;

    @JsonProperty
    private String name;
}

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
@Schema(implementation = UserSer.class)
public enum User {
   ...
}

I believe the current problem resides in this line of the ModelResolver:

https://github.com/swagger-api/swagger-core/blob/0144bff2df1aba025412678a64c7e60f515d0b88/modules/swagger-core/src/main/java/io/swagger/v3/core/jackson/ModelResolver.java#L281-L285

Any class with Java enum type will always be serialised as a String Schema.

I found this to be quite hard to work around as I wished to reuse ModelResolver's logic for bean serialisation and I did not wish to duplicate that logic in a custom ModelConverter.

tl;dr:

  1. Jackson annotations are disregarded when serializing enum classes [feature request]
  2. ModelResolver will serialize a Bean enum class always as a StringSchema disregarding all annotations (@Schema(type = "object") does not work) [a bug imo]

As a QoL change for (2) I would recommend splitting out the bean serialisation from the main resolve method of ModelResolver to allow it to be invoked by subclasses which could then specify a custom base schema.

swarth100 avatar Sep 02 '20 17:09 swarth100

Hi guys, any idea how to workaround this problem with this dependency as we dont have @Schema annotation ?

georgiivanov9 avatar May 10 '22 08:05 georgiivanov9