我需要解析一个包含属性“triggers”的对象,该属性是List<Trigger>
。该列表可以包含两种类型的触发器:“自定义”和“事件”。
这是我的触发器类:
@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
类中的字段。我需要实现一种逻辑来解析类型为“事件”的EventTrigger
或类型为“自定义”的CustomTrigger
。如何使用
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
依赖项。