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

@JsonClassDiscriminator未生效无法修改JSON类鉴别器问题

问题描述

受项目架构设计、向后兼容性等要求约束,需要为某抽象类及其所有继承子类修改类鉴别器,理想状态下该鉴别器对应枚举类型。

尝试使用@JsonClassDiscriminator注解配置鉴别器字段时,kotlinx.serialization仍默认使用type作为鉴别器,与类中原有名为type的成员产生命名冲突;将类中type成员重命名测试后,发现框架依然使用type作为鉴别器字段。

由于相关类属于共享代码,除注解配置外希望尽量不修改类本身,否则会产生非向后兼容的变更,引发问题。

测试代码

从项目中抽离了测试代码用于复现该行为,代码如下:

fun main() {
    val derived = Derived("type", "name") as Base
    val json = Json {
        prettyPrint = true
        encodeDefaults = true
        serializersModule = serializers
    }.encodeToString(derived)
    print(json)
}

@Serializable
@JsonClassDiscriminator("source")
data class Derived(
    val type: String?,
    val name: String?,
) : Base() {
    override val source = FooEnum.A
}

@Serializable
@JsonClassDiscriminator("source")
abstract class Base {
    abstract val source: FooEnum
}

enum class FooEnum { A, B }

internal val serializers = SerializersModule {
    polymorphic(Base::class) {
        subclass(Derived::class)
    }
}
复现现象
  • 不修改类中type成员的名称时,运行抛出如下错误:

Exception in thread "main" java.lang.IllegalArgumentException:
Polymorphic serializer for class my.pack.Derived has property 'type'
that conflicts with JSON class discriminator. You can either change
class discriminator in JsonConfiguration, rename property with
@SerialName annotation or fall back to array polymorphism

  • 修改类中type成员的名称时,输出如下JSON,可明显看到JSON类鉴别器并未被修改:
{
    "type": "my.pack.Derived",
    "typeChanged": "type",
    "name": "name",
    "source": "A"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 08:45:38