gpt4 book ai didi

android - 如何使用带有 Kotlin 的 Room 和 moshi 在其中保存带有 JSON 数组的 JSON 对象

转载 作者:行者123 更新时间:2023-12-02 12:57:27 26 4
gpt4 key购买 nike

所以,我有这个 JSON 对象

{ 
"name": "News",
"infos":[
{ "title":"hello",
"content":"this is the content",
"recent":true
},
{ "title":"Tax",
"content":"The European Commission is considering possible tax benefits",
"recent":true
},
{ "title":"Tax",
"content":"The European Commission is considering possible tax benefits",
}
]

我需要使用 moshi 将此对象与 Room(Android) 持久化,以将此对象反序列化到我的数据类中

@JsonClass(generateAdapter = true)
@Entity(
tableName = "news"
)

data class News(
@ColumnInfo(name = "name")
val name:String = "News",

val infos:List<Info>,

@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
val id: Int){
}

@JsonClass(generateAdapter = true)
@Entity(tableName = "info",
foreignKeys = [
ForeignKey(entity = News::class, parentColumns = ["id"], childColumns = ["info_id"])
],
indices = [Index("info_id")])
data class Info(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
var id: Int,
val title : String,
val content: String,
val recent: Boolean?,
@ColumnInfo(name = "info_id")
val infoId: Int) {

}

我还创建了 Roomd 数据库和我的 @dao 类 @Insert fun。但是我得到这个错误:

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.example.data.Info> infos = null;

最佳答案

您缺少 TypeConverter。 Room 无法保存复杂的字段类型,如列表、日期、数组等。

请引用: https://developer.android.com/training/data-storage/room/referencing-data

关于android - 如何使用带有 Kotlin 的 Room 和 moshi 在其中保存带有 JSON 数组的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59335504/

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