swagger-api / swagger-api/swagger-core

Jackson annotations ignored on enum class

Open
#3,691 2 comments 10 reactions 1 assignee View on GitHub

@frantuma is already working on this.

Since Sep 22, 2020.

backlog
Dominant language
Java
Stars
7.5k
Forks
2.3k
Avg merge
18h 1m
Merged PRs (30d)
10

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.