Search code examples
jsonkotlinadaptermoshi

How to parse a field in 2 different ways with Moshi


I need to parse an object that contains a property "triggers" which is an List<Trigger>. This list can contain 2 type of triggers: Custom and Event. Here are my Trigger 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)

My object that I receive from server looks like this :

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

Using generated adapter on parsing I get on triggers only the fields from Trigger class. I need to implement a logic to parse an EventTrigger is type is "event" or an CustomTrigger if type is "custom".

How can I do this with Moshi? Do I need to write a manual parser for my Rule object?

Any idea is welcome. Thank you


Solution

  • This example from Moshi helped me to solve the parsing problem : https://github.com/square/moshi#another-example