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

Kotlin:使用Jackson实现枚举描述字段作为实体属性值的序列化

解决方案:让Jackson序列化枚举时输出指定的desc字段

嘿,我来帮你搞定这个Jackson序列化的问题!你的需求是让Thing类序列化后,state字段直接显示枚举的desc值,而不是枚举名或者整个枚举对象,这里有两种简单又靠谱的方法:

方法一:用@JsonValue注解直接标记枚举的目标字段

这是最简洁的方案,只要告诉Jackson序列化State枚举时,就用它的desc属性值就行。

修改你的State枚举类:

enum class State(@JsonValue val desc: String) {
    ACTIVE("In Use"), 
    INACTIVE("Not In Use")
}

或者如果习惯用 getter 方法的形式,也可以这样写:

enum class State(val desc: String) {
    ACTIVE("In Use"), 
    INACTIVE("Not In Use");

    @JsonValue
    fun serializeDesc(): String = desc
}

这样处理后,序列化Thing对象时,state字段就会直接输出desc的内容,完全符合你的需求:

"thing": { "name": "Thing's name", "state": "In Use" }

方法二:自定义枚举序列化器(适合需要灵活控制的场景)

如果后续你需要针对不同场景调整枚举的序列化逻辑,自定义序列化器会更灵活。

步骤1:实现自定义序列化器

class StateSerializer : JsonSerializer<State>() {
    override fun serialize(
        value: State?,
        gen: JsonGenerator?,
        serializers: SerializerProvider?
    ) {
        gen?.writeString(value?.desc)
    }
}

步骤2:给枚举类指定这个序列化器

@JsonSerialize(using = StateSerializer::class)
enum class State(val desc: String) {
    ACTIVE("In Use"), 
    INACTIVE("Not In Use")
}

这样同样能让state字段输出你想要的desc值。

验证效果

不管用哪种方法,运行下面的测试代码:

val thing = Thing("Thing's name", State.ACTIVE)
val objectMapper = ObjectMapper().registerModule(KotlinModule())
val json = objectMapper.writeValueAsString(mapOf("thing" to thing))
println(json)

都会得到你期望的输出:

{"thing":{"name":"Thing's name","state":"In Use"}}


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 15:59:09