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

如何让Kotlin枚举通过ObjectMapper序列化输出intValue数值?

解决Kotlin枚举序列化输出intValue的问题

下面是两种标准实现方式,可让ObjectMapper序列化时输出枚举的intValue数值而非枚举名称:

方法一:使用@JsonValue注解(推荐,侵入性低)

直接在枚举的intValue属性上添加Jackson的@JsonValue注解,明确告诉序列化器用该值作为输出:

import com.fasterxml.jackson.annotation.JsonValue

enum class SEVERITY(@JsonValue val intValue: Int) {
    DEBUG(1),
    VERBOSE(2),
    INFO(3),
    WARN(4),
    ERROR(5),
    CRITICAL(6)
}

也可以通过getter方法添加注解,效果完全一致:

import com.fasterxml.jackson.annotation.JsonValue

enum class SEVERITY(val intValue: Int) {
    DEBUG(1),
    VERBOSE(2),
    INFO(3),
    WARN(4),
    ERROR(5),
    CRITICAL(6);

    @JsonValue
    fun serializeValue() = intValue
}

配置完成后,序列化SEVERITY.DEBUG就会输出1,完全满足需求。

方法二:自定义序列化器(无侵入,适合无法修改枚举类的场景)

如果不能修改原枚举类,可以自定义序列化逻辑并注册到ObjectMapper中:

1. 实现枚举序列化器

import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.JsonSerializer
import com.fasterxml.jackson.databind.SerializerProvider

class SeveritySerializer : JsonSerializer<SEVERITY>() {
    override fun serialize(value: SEVERITY?, gen: JsonGenerator?, serializers: SerializerProvider?) {
        gen?.writeNumber(value?.intValue ?: 0)
    }
}

2. 注册到ObjectMapper

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.registerKotlinModule

val objectMapper = ObjectMapper().apply {
    registerKotlinModule() // 必须注册Kotlin模块,否则可能无法识别Kotlin枚举
    addSerializer(SEVERITY::class.java, SeveritySerializer())
}

使用这个配置好的objectMapper序列化枚举,就能输出对应的int数值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 21:22:34