4

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

Gabrielle
  • 4,933
  • 13
  • 62
  • 122

2 Answers2

2

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.

Jesse Wilson
  • 39,078
  • 8
  • 121
  • 128
  • I tried with PolymorphicJsonAdapterFactory but it parse it as Trigger in my case, and not in a subclass of Trigger. – Gabrielle Apr 19 '19 at 13:10
1

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

Gabrielle
  • 4,933
  • 13
  • 62
  • 122