gpt4 book ai didi

android - 如何在不使用 JSON 和 GSON 的情况下将 HashMap 保存在 Room 数据库中?

转载 作者:行者123 更新时间:2023-12-05 05:06:57 25 4
gpt4 key购买 nike

我试图将 Address 存储在 HashMap 中,但编译器给出了错误:无法弄清楚如何将此字段保存到数据库中。您可以考虑为其添加类型转换器。私有(private)java.util.HashMap地址;

 error: 
Cannot figure out how to save this field into database. You can consider adding a type converter for it. private java.util.HashMap<java.lang.String, java.lang.String> address;

我正在使用 MapTypeConverter 但它不起作用

object MapTypeConverter {

@TypeConverter
@JvmStatic
fun stringToMap(value: JsonElement): Map<String, String> {
return Gson().fromJson(value, object : TypeToken<Map<String, String>>() {}.type)
}

@TypeConverter
@JvmStatic
fun mapToString(value: Map<String, String>?): String {
return if(value == null) "" else Gson().toJson(value)
}
}

房间实体

@Entity
data class User(
var ownerName: String? = null,
var shopNumber: String? = null,
var deviceToken: String? = null,
var altNumber: String? = null,
var address: Map<String, String>? = null
) {
@PrimaryKey(autoGenerate = false)
var uId: String = "NA"
}

应用数据库

@Database(
entities = [User::class,ProductDetails::class,CategoryDetails::class],
version = 1
)
@TypeConverters(ConverterListToString::class,MapTypeConverter::class)
abstract class AppDatabase : RoomDatabase(){

abstract fun getUserDao(): UserDao
abstract fun getProductDao(): ProductDao
abstract fun getCategoryDao(): CategoryDao

companion object{

@Volatile
private var instance: AppDatabase? = null
private val LOCK = Any()

operator fun invoke(context: Context) = instance ?: synchronized(LOCK){
instance ?: buildAppDataBase(context).also {
instance = it
}
}

private fun buildAppDataBase(context: Context) =
Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
"TradersDatabase.db"
).build()
}
}

最佳答案

使用String代替JsonElement

object MapTypeConverter {

@TypeConverter
@JvmStatic
fun stringToMap(value: String): Map<String, String> {
return Gson().fromJson(value, object : TypeToken<Map<String, String>>() {}.type)
}

@TypeConverter
@JvmStatic
fun mapToString(value: Map<String, String>?): String {
return if(value == null) "" else Gson().toJson(value)
}
}

你的实体应该是这样的

@Entity
data class User(
var ownerName: String? = null,
var shopNumber: String? = null,
var deviceToken: String? = null,
var altNumber: String? = null,

@TypeConverters(MapTypeConverter::class)
var address: Map<String, String>? = null
) {
@PrimaryKey(autoGenerate = false)
var uId: String = "NA"
}

关于android - 如何在不使用 JSON 和 GSON 的情况下将 HashMap 保存在 Room 数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59550722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com