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

Spring Kotlin控制器返回空对象:is前缀DataClass属性问题

解决Kotlin DataClass中is前缀属性Spring序列化空对象问题

问题原因

Spring默认用Jackson序列化Kotlin数据类时,对布尔类型的is前缀属性,会自动去掉is前缀生成JSON字段名(比如isActive: Boolean会序列化为"active": true)。但你的isActive是String类型,这就导致Jackson序列化逻辑混乱:Kotlin为该属性生成的getter是isActive()(符合Kotlin命名规范),但Jackson无法匹配String类型is前缀属性的序列化规则,最终导致该字段无法被正确序列化,进而返回空对象。

解决方案

1. 单个字段:用@JsonProperty指定序列化字段名

直接在isActive属性上添加@JsonProperty注解,强制Jackson使用指定的字段名输出,这是最直接的解决方式:

import com.fasterxml.jackson.annotation.JsonProperty

data class Response(
    public val result: ResponseResult,
    val status: Int,
    val message: String
)

data class ResponseResult(
    @JsonProperty("isActive")
    val isActive: String
)

2. 全局配置:修改Jackson Kotlin模块规则

如果项目中有大量类似的is前缀非布尔属性,可以全局配置Jackson,让它保留is前缀作为JSON字段名:

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.fasterxml.jackson.module.kotlin.KotlinFeature
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

@Configuration
class JacksonConfig {
    @Bean
    fun jacksonObjectMapper(): ObjectMapper {
        return ObjectMapper()
            .registerModule(
                KotlinModule.Builder()
                    .configure(KotlinFeature.SERIALIZE_IS_AS_PROPERTY_NAME, true)
                    .build()
            )
    }
}

这个配置会让Jackson对所有Kotlin的is前缀属性(无论类型)都保留原字段名序列化,无需逐个字段加注解。

3. 手动指定getter方法(不推荐)

通过手动定义getter方法,让Jackson能识别对应的字段名,但这种方式会破坏数据类的简洁性,仅作参考:

data class ResponseResult(
    val isActive: String
) {
    // 手动定义getter,让Jackson识别为isActive字段
    fun getIsActive(): String = isActive
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 07:52:12