我需要解析一个包含属性“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
依赖项。
来自Moshi
的这个例子帮助我解决了解析问题:https://github.com/square/moshi#another-example