Gabrielle
Gabrielle

Reputation: 4981

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

Upvotes: 4

Views: 2953

Answers (2)

Gabrielle
Gabrielle

Reputation: 4981

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

Upvotes: 0

Jesse Wilson
Jesse Wilson

Reputation: 40603

Take a look at the PolymorphicJsonAdapterFactory.

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

Note that it needs the optional moshi-adapters dependency.

Upvotes: 4

Related Questions