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

从SwaggerFox迁移至OpenApi,如何配置值对象保持原UI展示?

解决OpenApi中值对象展示格式问题

针对你从SwaggerFox迁移到OpenApi后,带@JsonValue注解的值对象展示格式变化的问题,有几种可行的配置方案:

方案1:在值对象上直接添加@Schema注解

直接在UserId类上指定Schema的类型和格式,让OpenApi将其视为UUID对应的字符串类型:

import io.swagger.v3.oas.annotations.media.Schema
import com.fasterxml.jackson.annotation.JsonValue
import java.util.UUID

data class UserId(
    @JsonValue
    @Schema(type = "string", format = "uuid")
    val value: UUID
)

配置后,Swagger UI里userId会展示为"userId": "string"(实际会识别为UUID格式的字符串)。

方案2:全局配置模型替换(类似SwaggerFox的directModelSubstitute)

如果有大量值对象需要统一处理,可以通过SpringDoc的配置实现全局替换:

方式A:使用OpenApiCustomiser

import io.swagger.v3.oas.models.OpenApi
import io.swagger.v3.oas.models.media.StringSchema
import org.springdoc.core.customizers.OpenApiCustomiser
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import java.util.UUID

@Configuration
class OpenApiConfig {
    @Bean
    fun valueObjectModelSubstitute(): OpenApiCustomiser {
        return OpenApiCustomiser { openApi: OpenApi ->
            openApi.components.schemas.values.forEach { schema ->
                if (schema.name == "UserId") {
                    schema.type = "string"
                    schema.format = "uuid"
                    schema.properties.clear()
                }
                // 可添加更多值对象的处理逻辑
            }
        }
    }
}

方式B:自定义ModelConverter

这种方式能自动识别所有带@JsonValue注解的值对象,灵活性更高:

import com.fasterxml.jackson.annotation.JsonValue
import io.swagger.v3.core.converter.ModelConverter
import io.swagger.v3.core.converter.ModelConverterContext
import org.springdoc.core.converters.ModelConverterUtils
import org.springframework.stereotype.Component
import java.lang.reflect.Field
import java.util.UUID

@Component
class ValueObjectModelConverter : ModelConverter {
    override fun resolve(type: java.lang.reflect.Type, context: ModelConverterContext, chain: Iterator<ModelConverter>): Schema<*>? {
        val clazz = ModelConverterUtils.getSchemaClass(type)
        val jsonValueField: Field? = clazz.declaredFields.firstOrNull { it.isAnnotationPresent(JsonValue::class.java) }
        
        if (jsonValueField != null) {
            return when (jsonValueField.type) {
                UUID::class.java -> Schema<Any>().type("string").format("uuid")
                String::class.java -> Schema<Any>().type("string")
                // 可扩展其他类型的处理逻辑
                else -> chain.next().resolve(type, context, chain)
            }
        }
        return chain.next().resolve(type, context, chain)
    }
}

该转换器会自动将所有带@JsonValue注解的 value 对象,替换为对应字段类型的Schema,不再展示包含value属性的嵌套结构。

验证效果

配置完成后重启服务,Swagger UI中userId的展示会恢复为:

"userId": "string"

内容的提问来源于stack exchange,提问作者J.Doe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 10:10:16