Android 房间。如何在数据库中存储动态字段?
服务器可以返回字符串或字符串数组作为同一请求的结果。这是无法改变的。 例子: { “值”:“val” } { “价值”:[ “val1”, “val2” ] } 我知道我可以编写一个TypeAdapter进行改装,然后我就可以得到这些数据。 但我不明白我如何将这些数据保存在数据库“房间”中 我正在努力做到以下几点: 我创建了一个带有一些字段的接口。 可以是String或String[]的字段的类型为Any(kotlin)。然后我创建了两个类来实现这个接口。在一个类中,此字段的类型为String,在另一个类中,此字段的类型为String[]。 然后我创建了一个TypeConverter,并注册了它 需要保存在数据库中的实体:Android 房间。如何在数据库中存储动态字段?,android,database,kotlin,Android,Database,Kotlin,服务器可以返回字符串或字符串数组作为同一请求的结果。这是无法改变的。 例子: { “值”:“val” } { “价值”:[ “val1”, “val2” ] } 我知道我可以编写一个TypeAdapter进行改装,然后我就可以得到这些数据。 但我不明白我如何将这些数据保存在数据库“房间”中 我正在努力做到以下几点: 我创建了一个带有一些字段的接口。 可以是String或String[]的字段的类型为Any(kotlin)。然后我创建了两个类来实现这个接口。在一个类中,此字段的类型为String,
@Entity(tableName = "surveys_table")
data class Survey(
...
@SerializedName("questions")
private var questions: List<Question>
)
实现此接口的2个类
data class QuestionWithArrayValues(
...,
val _value: List<String>?
) : Question
data class QuestionWithStringValues(
...,
val _value: String?
) : Question
但我一直在犯错误:
无法确定如何将此字段保存到数据库中。你可以考虑
为它添加一个转换器
我还尝试使用抽象类而不是Question
接口。我不确定你是否能做到这一点,有没有办法摆脱这种情况。。。
有人知道我应该做什么吗?尝试向数据类
私有变量问题:列表中的字段添加?
。卸载应用程序并重新运行使生活变得轻松,并将其存储为数组(将单个字符串转换为1的数组),而不管服务器是什么sends@TimCastelijns谢谢我明天试试
data class QuestionWithArrayValues(
...,
val _value: List<String>?
) : Question
data class QuestionWithStringValues(
...,
val _value: String?
) : Question
class QuestionsConverter{
@TypeConverter
fun fromQuestionsDbList(questions: List<Question>?): String? {
if (questions == null) {
return null
}
val gson = Gson()
return try {
val type = object : TypeToken<List<QuestionWithStringValues>>() { }.type
gson.toJson(questions, type)
} catch (exception: Exception) {
val type = object : TypeToken<List<QuestionWithArrayValues>>() { }.type
gson.toJson(questions, type)
}
}
@TypeConverter
fun toQuestionsDbList(questions: String?): List<Question>? {
if (questions == null) {
return null
}
val gson = Gson()
return try {
val type = object : TypeToken<List<QuestionWithStringValues>>() {}.type
gson.fromJson<List<QuestionWithStringValues>>(questions, type)
} catch (exception: Exception) {
val type = object : TypeToken<List<QuestionWithArrayValues>>() {}.type
gson.fromJson<List<QuestionWithArrayValues>>(questions, type)
}
}
}
@TypeConverters(QuestionsConverter::class)
abstract class AppDatabase : RoomDatabase() ...