How to parse polymorphic objects in Kotlin using Moshi How to parse polymorphic objects in Kotlin using Moshi json json

How to parse polymorphic objects in Kotlin using Moshi


I've changed @field:Json to Json, Products to products and SpecialProductsComponent fields. So finally I got:

sealed class HomeComponent(@Json(name = "_type") val type: HomeContentType) {    data class BannerComponent(        @Json(name = "_id")        val id: String,        val image: String    ) : HomeComponent(HomeContentType.banner)    data class SpecialProductsComponent(        @Json(name = "_id")        val id: String,        val style: String,        val products: List<Product>    ) : HomeComponent(HomeContentType.products)    data class CarouselBannerComponent(        @Json(name = "_id")        val id: String,        val style: String,        val images: List<String>    ) : HomeComponent(HomeContentType.carousel)}enum class HomeContentType {    @Json(name = "banner")    banner,    @Json(name = "products")    products,    @Json(name = "carousel")    carousel}

and now it seems that all works fine. I checked it with following code:

fun main() {    val moshi = Moshi.Builder()        .add(            PolymorphicJsonAdapterFactory.of(HomeComponent::class.java, "_type")                .withSubtype(HomeComponent.BannerComponent::class.java, HomeContentType.banner.name)                .withSubtype(HomeComponent.SpecialProductsComponent::class.java, HomeContentType.products.name)                .withSubtype(HomeComponent.CarouselBannerComponent::class.java, HomeContentType.carousel.name)        )        .add(KotlinJsonAdapterFactory())        .build()    val json = """[  {    "image": "http://image1.url",    "_id": "carousel1",    "style": "SLIDE",    "_type": "banner"  },  {    "products": [],    "_id": "id1",    "style": "CARD",    "_type": "products"  },  {    "images": [      "http://image1.url",      "http://image1.url",      "http://image1.url"    ],    "_id": "carousel1",    "style": "SLIDE",    "_type": "carousel"  }]    """.trimIndent()    val adapter =        moshi.adapter<List<HomeComponent>>(Types.newParameterizedType(List::class.java, HomeComponent::class.java))    val result = adapter.fromJson(json)    println(result)}