Search code examples
androidkotlinmvvmandroid-roomtypeconverter

Using TypeConverter to insert map to the room database


I'd like to add TypeConverter to my app, but I don't know how I can add Maps to my Converter class. I've already covered I think all necessary entities in my app. Here's some code:

@Entity(tableName = "map_table")
data class dbtable(
    @PrimaryKey
    @ColumnInfo
    @TypeConverters(MyConverter::class)
    val data: Map<String, Float>? = null
)

In database class, I've added annotation

@TypeConverters(MyConverter::class)
abstract class myDb() : RoomDatabase() {
...
}

My DAO fun looks like this:

@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun test(model: dbtable)

Now, how I can implement map in my converter class? I'm kinda lost in it.


Solution

  • class MyConverter {
       
            @TypeConverter
            fun jsonToMap(value: String): Map<String, Float>? {
                val mapType = object : TypeToken<Map<String, Float>?>() {}.type
                return Gson().fromJson(value, mapType)
            }
    
            @TypeConverter
            fun mapToJson(map: Map<String, Float>?): String {
                val gson = Gson()
                return gson.toJson(map)
            }
        }
    }
    
    @Entity(tableName = "map_table")
    @TypeConverters(MyConverter::class)
    data class dbtable(
        @PrimaryKey
        @ColumnInfo
        val data: Map<String, Float>? = null
    )