如何使用 Moshi 以两种不同的方式解析字段

How to parse a field in 2 different ways with Moshi

我需要解析一个包含 属性 "triggers" 的对象,它是一个 List<Trigger>。此列表可以包含 2 种类型的触发器:自定义和事件。 这是我的触发器 classes :

  @JsonClass(generateAdapter = true)
    open class Trigger(open val type: String,
                       open val source: String,
                       open val tags: Properties? = mutableMapOf())

  @JsonClass(generateAdapter = true)
    data class CustomTrigger(override val type: String,
                             override val source: String,
                             override val tags: Properties?,
    //some other fields
    ) : Trigger(type, source, tags)

@JsonClass(generateAdapter = true)
data class EventTrigger(override val type: String,
                         override val source: String,
                         override val tags: Properties?,
    //some other fields
) : Trigger(type, source, tags)

我从服务器收到的对象如下所示:

@JsonClass(generateAdapter = true)
data class Rule(val id: String,
                val triggers: MutableList<Trigger>,
//some other fields
)

在解析时使用生成的适配器,我只触发来自 Trigger class 的字段。我需要实现一个逻辑来解析 EventTrigger is type is "event" or an CustomTrigger if type is "custom".

如何使用 Moshi 执行此操作? 我需要为我的 Rule 对象编写手动解析器吗?

欢迎任何想法。谢谢

看看PolymorphicJsonAdapterFactory

Moshi moshi = new Moshi.Builder() 
    .add(PolymorphicJsonAdapterFactory.of(HandOfCards.class, "hand_type")
        .withSubtype(BlackjackHand.class, "blackjack")
        .withSubtype(HoldemHand.class, "holdem")) 
    .build(); 

请注意,它需要可选的 moshi-adapters 依赖项。

Moshi 中的这个示例帮助我解决了解析问题: https://github.com/square/moshi#another-example