I have a Plant data class, that has a PlantType sealed class parameter. I am using a Room local db, but when I try to parse it it fails. It works for other classes that has initializable class parameters.
Thanks for the help in advance.
The error:
java.lang.RuntimeException: Failed to invoke private com.tenyitamas.mylittlegarden.domain.util.PlantType() with no args
at com.tenyitamas.mylittlegarden.data.util.Converters.fromPlantsJson(Converters.kt:99)
// Comment: Converters.kt: 99 is the from json part of the Converters code, I included.
Plant.kt:
data class Plant(
val type: PlantType,
val upgrades: Upgrades
)
PlantType.kt:
sealed class PlantType {
object Carrot : PlantType()
object Tomato : PlantType()
object Cucumber : PlantType()
object Lettuce : PlantType()
object Strawberry : PlantType()
}
Converters.kt
@TypeConverter
fun fromPlantsJson(json: String): List<Plant> {
return jsonParser.fromJson<ArrayList<Plant>>(
json,
object : TypeToken<ArrayList<Plant>>(){}.type
) ?: emptyList()
}
@TypeConverter
fun toPlantsJson(plants: List<Plant>): String {
return jsonParser.toJson(
plants,
object : TypeToken<ArrayList<Plant>>(){}.type
) ?: "[]"
}
Your PlantType
sealed class has only objects inside it. You can just use an enum for this.
enum class PlantType {
Carrot, Tomato, Cucumber, Lettuce, Strawberry
}
And most likely your jsonParser
will be able to serialize this enum.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.