无法弄清楚如何将该字段保存到Android Room数据库中

时间:2019-09-07 07:17:45

标签: android android-room typeconverter

我正在使用Android Room开发数据库,​​并且希望将JSON这样的数据存储到数据库中。

@Entity(tableName = "bank_info")
data class BankInfo(

    @PrimaryKey
    @SerializedName("id")
    @ColumnInfo(name = "id") val id: Long,

    @SerializedName("name")
    @ColumnInfo(name = "name") val name: String,

    @TypeConverters(BankTypeConverter::class)
    @SerializedName("banks")
    @ColumnInfo(name = "banks") val banks: List<Bank>,

){
    data class Bank (
        @SerializedName("bankid")
        @ColumnInfo(name = "id") val id: Long,

        @SerializedName("name")
        @ColumnInfo(name = "name") val name: String

    )
}

它显示错误:

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<com.bank.wallet.BankInfo.Bank> banks = null;
                                                                                                      ^

我已搜索上述错误,并使用@TypeCovert如下:

class BankTypeConverter {

    @TypeConverter
    open fun lisiToString(list: List<Bank>): String {
        if (list == null || list.size === 0) {
            return ""
        }
        val gson = Gson()
        val type = object : TypeToken<List<Bank>>() {

        }.type
        val json = gson.toJson(list, type)

        return json
    }

    @TypeConverter
    open fun StringToArray(value: String): List<Bank> {

        val gson = Gson()
        val type = object : TypeToken<List<Bank>>() {

        }.type
        return gson.fromJson(value, type)

    }

}

但是它不起作用,我错过了什么吗?

如何为上述格式编写@TypeCovert

谢谢。

1 个答案:

答案 0 :(得分:0)

这是一个代码段

class Converter {

    @TypeConverter
    public static List<Bank> restoreBankList(String listOfString) {
        return new Gson().fromJson(listOfString, new TypeToken<List<Bank>>() {}.getType());
    }

    @TypeConverter
    public static String saveListAsString(List<Bank> listOfString) {
        return new Gson().toJson(listOfString);
    }

}

现在您应该告诉RoomDatabase您正在使用@TypeConverter

@Database(entities = YourClass, version = 1)
@TypeConverters({Converter.class})
public abstract class RadarDatabaseHolder extends RoomDatabase {



// here is your usual code

}

类型将在执行数据库操作时自动转换