Learning Kotlin Language

Support JSON and Polymorphic Classes With Moshi Kotlin Made Easy

How do we support Abstract Class Implementations or Sealed Class with Moshi Kotlin?

Photo by Ben Wicks on Unsplash

When we have a JSON to convert to Class Object in Java, we can use Gson, Jackson. In Kotlin, the most popular one is Moshi.

We usually support 1–1 class to JSON as below

open class Base(val number: Int)fun process() {
val moshi: Moshi =
Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
val adaptor: JsonAdapter<Base> = moshi.adapter(Base::class.java) val base = Base(1)
println("Base ${adaptor.toJson(base)}")
}

This is all good. From the above, we can serialize to JSON as below.

Base {"number":1}

What about inherited classes?

Let’s assume we have two children's classes as below.

class SimpleChild(val item: String): Base(1)
class DynamicChild(val item: String, number: Int): Base(1)

If we use the same based adaptor as below

val moshi: Moshi =…

--

--