当前位置: 首页 > 知识库问答 >
问题:

错误室数据库:无法确定如何将该字段保存到数据库中。您可以考虑为其添加类型转换器

蒋培
2023-03-14

当我想将我的JSON记录到房间数据库中时,我遇到了一个问题。

我的数据类是:

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?

共有1个答案

锺离明煦
2023-03-14
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()
 类似资料: