I'm trying to store Map<String, String>
to Room database.
Json is like below.
{
"version": 1,
"data": {
"en": {"name": "english"},
"ko": {"name": "korean"},
"de": {"name": "germany"}
}
}
Entity is like below.
@Entity
data class Translation(
@PrimaryKey(autoGenerate = true)
val version: Int,
@SerializedName("data")
@Embedded
val data: Data
) {
data class Data(
@SerializedName("en")
val english: Map<String, String>,
@SerializedName("ko")
val korean: Map<String, String>,
@SerializedName("de")
val german: Map<String, String>
)
}
Room Database class is like.
@Database(
entities = [
Translation::class
],
version = 1,
exportSchema = false
)
@TypeConverters(ClassTypeConverter::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun translationDao(): TranslationDao
}
At last, ClassTypeConvert is below.
object MapTypeConverter {
@TypeConverter
fun stringToMap(value: JsonElement): Map<String, String> {
return Gson().fromJson(value, object : TypeToken<Map<String, String>>() {}.type)
}
@TypeConverter
fun mapToString(value: Map<String, String>?): String {
return if(value == null) "" else Gson().toJson(value)
}
}
But showing an error,
Cannot figure out how to save this field into database. You can consider adding a type converter for it.
private final java.util.Map<java.lang.String, java.lang.String> english = null;
Is this wrong way to save Map type to Room database?