Spring Doc Open API shows invalid field name on swagger ui

Viewed 256

There is an invalid model shown on swagger UI when there is only one lowercase letter at the beginning of the field name.

My Kotlin model:

class TrendEvaluationModel(
    val xAxisValue: Int,
    val yAxisValue: Int,
    val customValue: Int?
)

What is shown on swagger UI:

{
  "customValue": 1,
  "xaxisValue": 1,
  "yaxisValue": 1
}

I've tried:

  1. @Parameter annotation with specified name attribute but it does not work.
  2. @Schema annotation with specified name attribute but it does not work.
  3. @JsonProperty("xAxisValue") and it worked but not as expected - the model on swagger showed two fields then (xaxisValue and xAxisValue) but I need only one of them (xAxisValue).

Appreciate your help.

NOTE: There is no issue if there are two or more lowercase letters at the beginning of the field name

1 Answers

Applying the @Schema annotation to the constructor fields to change the field names in Swagger UI did not have an effect. So I made those fields private and added new fields that point to the private fields. I also added @Schema and @JsonProperty annotations to the new fields to change how they show up in Swagger UI and the API request/response respectively. The final class looked like below:

import com.fasterxml.jackson.annotation.JsonProperty
import io.swagger.v3.oas.annotations.media.Schema

class TrendEvaluationModel(
    @Schema(hidden = true)
    private val xAxisVal: Int,
    @Schema(hidden = true)
    private val yAxisVal: Int,
    val customValue: Int?
) {
    val xAxisValue: Int
        @Schema(name = "xAxisValue")
        @JsonProperty("xAxisValue")
        get() = xAxisVal

    val yAxisValue: Int
        @Schema(name = "yAxisValue")
        @JsonProperty("yAxisValue")
        get() = yAxisVal
}

This class shows up like below, with the correct field names, in Swagger UI:

{
  "customValue": 0,
  "xAxisValue": 0,
  "yAxisValue": 0
}

You can find a working sample app that uses this class on github

Related