Moshi life pro tip. I hope you love and hate this ...
# squarelibraries
t
Moshi life pro tip. I hope you love and hate this as much as I do. Need custom adapter behaviors but don't feel like wiring up the DI to get your adapter into the dagger graph? Just lie to it and hand write it! Moshi will reflect it into existence later!
Copy code
@JsonClass(generateAdapter = true, generator = "hand-written")
sealed class ClientMessage {
  val type: String
    get() = this.javaClass.name

  companion object Unknown : ClientMessage()
}

@JsonClass(generateAdapter = true)
data class Launch(
    val request: JobRequest
) : ClientMessage()

@Keep
class ClientMessageJsonAdapter(private val moshi: Moshi) : JsonAdapter<ClientMessage>() {

  @Suppress("UNCHECKED_CAST")
  private val actual by lazy {
    PolymorphicJsonAdapterFactory.of(
        ClientMessage::class.java,
        "type",
    )
        .withSubtype(Launch::class.java, Launch::class.java.name)
        .withDefaultValue(ClientMessage.Unknown)
        .create(ClientMessage::class.java, emptySet(), moshi) as JsonAdapter<ClientMessage>
  }

  override fun fromJson(reader: JsonReader): ClientMessage? {
    return actual.fromJson(reader)
  }

  override fun toJson(writer: JsonWriter, value: ClientMessage?) {
    actual.toJson(writer, value)
  }
}