[英]How to parse objects that has a sealed class param in kotlin android development using Room?
我有一个工厂数据 class,它有一个 PlantType 密封 class 参数。 我正在使用 Room 本地数据库,但是当我尝试解析它时它失败了。 它适用于具有可初始化 class 参数的其他类。
我在这里先向您的帮助表示感谢。
错误:
java.lang.RuntimeException:无法调用没有参数的私有 com.tenyitamas.mylittlegarden.domain.util.PlantType()
在 com.tenyitamas.mylittlegarden.data.util.Converters.fromPlantsJson(Converters.kt:99)
// 注释:Converters.kt: 99 是来自 json 部分的转换器代码,我包括在内。
植物.kt:
data class Plant(
val type: PlantType,
val upgrades: Upgrades
)
植物类型.kt:
sealed class PlantType {
object Carrot : PlantType()
object Tomato : PlantType()
object Cucumber : PlantType()
object Lettuce : PlantType()
object Strawberry : PlantType()
}
转换器.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
) ?: "[]"
}
您的PlantType
密封 class 里面只有物体。 您可以为此使用枚举。
enum class PlantType {
Carrot, Tomato, Cucumber, Lettuce, Strawberry
}
并且很可能您的jsonParser
将能够序列化此枚举。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.