Ok so i have the following Json Pojo:
data class JCategory(
val id: Int,
val name: String,
val image: String?,
val color: String?,
val categories: List<JCategory>?,
val products: List<JProduct>?
)
And i want to write a customs deserialiser, so the final object will look like this:
data class Category(
val id: Int,
val name: String,
val image: String?,
val color: String?,
val list: List<Any>
)
Basically, the mappings are:
JCategory -> Category
JProduct -> Prod1 / Prod2
based on some value inside JProduct
The JCategory two lists will be joint into 1, in which will contain more JCategory plus Prod1/Prod2.
Is this a valid and efficient way of mapping the data in this adapter according to Moshi?
@FromJson fun fromJson(category: JCategory): CategoryProduct {
val prods = category.products
val cats = category.categories
val list = mutableListOf<Any>()
if (prods != null && prods.size > 0) {
prods.forEach {
list.add(if (it.isMain == 1) {
P1(
...
)
} else {
P2(
...
)
})
}
}
if (cats != null && cats.size > 0){
cats.forEach {
list.add(fromJson(it))
}
}
return CategoryProduct(
category.id,
category.name,
category.image.emptyToNull(),
parsedColor,
category.parentId,
list
)
}
Notice that i have a JCategory and inside a list of the same object,
so i thought the Adapter would parse this automatically but it doesn't. So i tried list.add(fromJson(it))
and it worked.
So my questions are:
- is
list.add(fromJson(it))
the proper way of handling cases like this? - how can i map an object to another one/other based on some property inside it? The fromJson can only return 1 type of transformed object.