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

Spring Rest配置自定义JsonConfiguration实现类层级序列化带type字段

实现Spring中Kotlinx Serialization自定义classDiscriminator配置

要让你的继承层级类在JSON响应中自动带上type字段(值为@SerialName指定的名称),核心是给Spring配置自定义的Kotlinx Serialization Json实例,设置classDiscriminator = "type"。下面分场景一步步来实现:

1. 确保依赖配置正确

首先确认项目中引入了Spring Web和Kotlinx Serialization相关依赖(以Gradle Kotlin DSL为例):

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web") // 或webflux
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0")
}

同时在application.properties/application.yml中开启Kotlinx Serialization作为默认JSON序列化器:

spring.jackson.serialization.use-kotlinx-serialization=true

2. 配置自定义Json实例(Spring MVC场景)

创建一个配置类,生成带有自定义规则的KotlinxSerializationJsonHttpMessageConverter Bean:

import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.converter.json.KotlinxSerializationJsonHttpMessageConverter
import kotlinx.serialization.json.Json

@Configuration
class JsonSerializationConfig {

    @Bean
    fun customKotlinxSerializationConverter(): KotlinxSerializationJsonHttpMessageConverter {
        val customJson = Json {
            // 核心配置:指定类鉴别器字段名为"type"
            classDiscriminator = "type"
            // 可选配置:根据需求开启
            prettyPrint = true // 格式化JSON输出
            encodeDefaults = true // 输出默认值字段
            ignoreUnknownKeys = true // 忽略未知字段避免反序列化报错
        }
        return KotlinxSerializationJsonHttpMessageConverter(customJson)
    }
}

3. 配置自定义Json实例(Spring WebFlux场景)

如果用的是WebFlux,需要通过WebFluxConfigurer来配置编解码器:

import org.springframework.context.annotation.Configuration
import org.springframework.http.codec.ServerCodecConfigurer
import org.springframework.web.reactive.config.WebFluxConfigurer
import kotlinx.serialization.json.Json

@Configuration
class WebFluxJsonConfig : WebFluxConfigurer {

    override fun configureHttpMessageCodecs(configurer: ServerCodecConfigurer) {
        val customJson = Json {
            classDiscriminator = "type"
            encodeDefaults = true
        }
        // 给编解码器设置自定义Json实例
        configurer.defaultCodecs().kotlinxSerializationJsonDecoder(customJson)
        configurer.defaultCodecs().kotlinxSerializationJsonEncoder(customJson)
    }
}

4. 验证类层级的序列化效果

确保你的父类和子类都正确标记@Serializable,子类加上@SerialName:

@Serializable
abstract class BaseExample(open val id: String)

@Serializable
@SerialName("example")
data class Example(override val id: String, val name: String) : BaseExample(id)

// 另一个子类示例
@Serializable
@SerialName("another_example")
data class AnotherExample(override val id: String, val value: Int) : BaseExample(id)

当控制器返回父类类型的对象时,响应会自动带上type字段:

@GetMapping("/example")
fun getExample(): BaseExample {
    return Example("1", "Test Demo")
}

返回的JSON结果会是:

{
  "type": "example",
  "id": "1",
  "name": "Test Demo"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:12:31