You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Doc Open API在Swagger UI显示无效字段名求助

问题解决:Kotlin单小写字母开头字段在Swagger UI的命名错误

问题重现

Kotlin模型类中,单个小写字母开头的驼峰字段(如xAxisValue),在Swagger UI中被错误转换为xaxisValue,而多小写字母开头的字段(如customValue)无此问题。尝试@Parameter、@Schema(name)无效,使用@JsonProperty会导致Swagger同时显示正确和错误的两个字段。

解决方案

方案1:配置Swagger使用Jackson的字段命名策略(推荐)

如果使用SpringDoc OpenAPI(主流Swagger实现),添加配置类让Swagger复用Jackson的ObjectMapper来解析字段名,确保和序列化逻辑一致:

@Configuration
class OpenApiConfig {
    @Bean
    fun springDocConfigProperties(): SpringDocConfigProperties {
        val props = SpringDocConfigProperties()
        // 开启Jackson映射器,让Swagger使用Jackson的字段命名规则
        props.isUseJacksonMapper = true
        return props
    }

    // 可选:添加OpenAPI基础配置
    @Bean
    fun customOpenApi(): OpenAPI {
        return OpenAPI()
            .info(Info().title("API文档").version("v1"))
    }
}

如果使用Springfox(旧版Swagger),配置ModelMapper启用Jackson注解支持:

@Configuration
class SwaggerConfig {
    @Bean
    fun docket(): Docket {
        return Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.your.project.package"))
            .paths(PathSelectors.any())
            .build()
            .modelMapper(customModelMapper())
    }

    private fun customModelMapper(): ModelMapper {
        val mapper = ModelMapper()
        // 启用Jackson注解,优先使用@JsonProperty等注解定义的字段名
        mapper.isJacksonAnnotationsEnabled = true
        return mapper
    }
}

方案2:结合@JsonProperty与@Schema隐藏冗余字段

如果无法修改全局配置,可给目标字段同时添加@JsonProperty和@Schema,确保字段名唯一:

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

class TrendEvaluationModel(
    @JsonProperty("xAxisValue")
    @Schema(name = "xAxisValue", required = true)
    val xAxisValue: Int,

    @JsonProperty("yAxisValue")
    @Schema(name = "yAxisValue", required = true)
    val yAxisValue: Int,

    val customValue: Int?
)

同时在application.yml中确保Jackson的命名策略正确:

spring:
  jackson:
    property-naming-strategy: LOWER_CAMEL_CASE

原理说明

该问题源于Swagger默认的字段命名策略对Kotlin单小写字母开头的驼峰字段处理逻辑错误,将xAxisValue错误转换为xaxisValue。让Swagger复用Jackson的命名策略或强制指定字段名,可确保字段名在Swagger UI和实际序列化中保持一致。

内容的提问来源于stack exchange,提问作者VadOS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 05:36:19