【问题标题】:Error Room Database: Cannot figure out how to save this field into database. You can consider adding a type converter for it错误室数据库:无法弄清楚如何将此字段保存到数据库中。您可以考虑为其添加类型转换器
【发布时间】:2020-10-25 08:09:23
【问题描述】:

当我想将我的 JSON 记录到 Room 数据库时遇到问题。

我的数据类是:

data class CurrentWeatherEntry(
@SerializedName("temperature")//
val temperature: Int,
@SerializedName("weather_code")
val weatherCode: Int,
@SerializedName("weather_icons")
val weatherIcons: List<String>,

)

{
    @PrimaryKey(autoGenerate = false)
    var id : Int = CURRENT_WEATHER_ID
}

I get error: Cannot figure out how to save this field into database. You can consider adding a type 
converter for it. 

private final java.util.List<java.lang.String> weatherIcons = null;

How to create converter?

【问题讨论】:

标签: database kotlin


【解决方案1】:
object Converter {
   private val gson = Gson()
   private val listTypeConverter = object : TypeToken<List<String>>() {}.type

   @TypeConverter
   @JvmStatic
   fun fromListToIcon(list: List<String>): String = gson.toJson(list, listTypeConverter)

  @TypeConverter
  @JvmStatic
  fun fromIconToList(icon: String): List<String> = gson.fromJson(icon, listTypeConverter)
}

然后在你的数据库顶部添加@TypeConverters(Converter::class)

@TypeConverters(Converter::class)
abstract class YourDB : RoomDatabase()

【讨论】:

    猜你喜欢
    • 2020-04-27
    • 2021-02-16
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 2023-01-15
    • 1970-01-01
    • 2019-05-17
    • 2019-10-04
    相关资源
    最近更新 更多