将Map <string,list <string =“” >>保存到Room Android

时间:2019-03-17 07:35:36

标签: java kotlin android-room

我有地图:

 @TypeConverters(StringListMapConverter::class)
    var variantColors: Map<String, List<String>>? =  null

和转换器:

class StringListMapConverter {
    @TypeConverter
    fun fromString(value: String): Map<String, List<String>> {
        val mapType = object : TypeToken<Map<String, List<String>>>() {

        }.type
        return Gson().fromJson(value, mapType)
    }

    @TypeConverter
    fun fromStringMap(map: Map<String, List<String>>): String {
        val gson = Gson()
        return gson.toJson(map)
    }
}

我收到错误消息:

error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.
    private java.util.Map<java.lang.String, ? extends java.util.List<java.lang.String>> variantColors;
                                                                                        ^   

我该如何解决我的问题?我应该在哪里为List添加这种类型的转换器?

1 个答案:

答案 0 :(得分:0)

在实例化@TypeConverters(StringListMapConverter::class)的地方定义此注释Room Database,例如:

@Database(...)
@TypeConverters(StringListMapConverter::class)
abstract class AppDatabase : RoomDatabase() {
    ...
}