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

如何使用Moshi根据type字段解析多类型Trigger列表?

用Moshi实现Trigger多态解析的解决方案

嗨,这个场景我开发时也碰到过!其实完全不需要给整个Rule类写手动解析器,只需要给Trigger配置多态Json适配器就能完美解决问题,下面给你一步步拆解:

核心思路

Moshi提供了PolymorphicJsonAdapterFactory,它可以根据你指定的字段(这里就是type)的值,自动判断应该把JSON解析成哪个子类。这样既不用手动写复杂的解析逻辑,也能保留自动生成适配器的便捷性。

具体实现步骤

1. 创建多态适配器工厂

先针对Trigger类创建一个多态工厂,绑定type字段和对应的子类:

import com.squareup.moshi.PolymorphicJsonAdapterFactory

// 配置多态规则:根据type字段的值匹配子类
val triggerPolymorphicFactory = PolymorphicJsonAdapterFactory.of(Trigger::class.java, "type")
    .withSubtype(CustomTrigger::class.java, "custom") // type为"custom"时解析为CustomTrigger
    .withSubtype(EventTrigger::class.java, "event")   // type为"event"时解析为EventTrigger

2. 初始化Moshi实例

把刚才的多态工厂添加到Moshi的Builder中,同时别忘了加上Kotlin适配器(因为你用了@JsonClass生成适配器):

import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory

val moshi = Moshi.Builder()
    .add(triggerPolymorphicFactory) // 添加上多态工厂
    .add(KotlinJsonAdapterFactory()) // 必须添加,否则无法处理Kotlin data class和@JsonClass注解
    .build()

3. 正常解析Rule对象

现在你可以直接用Moshi自动生成的Rule适配器来解析JSON了,它会自动处理triggers列表里的多态类型:

// 示例JSON
val ruleJson = """
{
  "id": "rule_001",
  "triggers": [
    {
      "type": "custom",
      "source": "user_action",
      "tags": {"module": "profile"},
      "custom_param": "custom_value" // CustomTrigger的额外字段
    },
    {
      "type": "event",
      "source": "system_event",
      "tags": {"priority": "high"},
      "event_code": "EVT_007" // EventTrigger的额外字段
    }
  ]
}
""".trimIndent()

// 获取Rule的适配器
val ruleAdapter = moshi.adapter(Rule::class.java)
val rule = ruleAdapter.fromJson(ruleJson)

// 验证解析结果:可以安全地判断类型并访问子类字段
rule?.triggers?.forEach { trigger ->
    when (trigger) {
        is CustomTrigger -> println("Custom触发器:${trigger.custom_param}")
        is EventTrigger -> println("Event触发器:${trigger.event_code}")
        else -> println("未知触发器类型")
    }
}

为什么不用给Rule写手动解析器?

因为Rule类里的其他字段都是普通类型,只有triggers需要多态处理。我们已经给Trigger配置了多态适配器,Moshi自动生成的Rule适配器会调用这个多态适配器来解析列表中的每个元素,完全不需要手动干预Rule的解析逻辑。

注意事项

  • 确保type字段的值和withSubtype中指定的字符串完全匹配(比如"custom"对应CustomTrigger,大小写也要一致)
  • 如果Trigger子类有额外字段,只要在data class中定义了,Moshi会自动解析这些字段
  • 别忘了添加KotlinJsonAdapterFactory,否则Moshi无法识别Kotlin的data class和@JsonClass生成的适配器

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:05:39