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

问题描述 投票:1回答:2

我需要解析一个包含属性“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对象编写手动解析器?

欢迎任何想法。谢谢

json kotlin adapter moshi
2个回答
0
投票

看看PolymorphicJsonAdapterFactory

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

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.