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