在Android上使用Room库时,我发现自己处于以下情况,我正在尝试创建一个商店,但我需要插入金额和相应的项目。但我不知道如何在房间里保存以下json格式,我真的很感谢你的帮助
[{
"id": 1,
"quantitiy": 3,
"item": {
"id": 1,
"name": "Huevos Frescampo X30",
"description": "Huevo Rojo A Insuperable, 30 Unidad(es). 1032680",
"price": 8950,
"createdAt": "2020-08-08T20:13:33",
"updatedAt": "2020-08-08T20:13:33"
}
}, {
"id": 2,
"quantitiy": 2,
"item": {
"id": 2,
"name": "Banano Criollo",
"description": "Banano Criollo",
"price": 630,
"createdAt": "2020-08-08T20:13:33",
"updatedAt": "2020-08-08T20:13:33"
}
}]
@Entity(tableName = "cart")
data class Cart (
@PrimaryKey
val id: Long,
val quantitiy: Long,
val item: ItemC
)
@Entity(tableName = "item")
data class ItemC (
val id: Long,
val name: String,
val description: String,
val price: Long,
val createdAt: String,
val updatedAt: String
)
在资产文件夹中创建一个json文件
class MockItemFactory constructor(
private val application: Application
) {
companion object {
const val KEY_FIRST_START = "FIRST_START"
}
fun generateMockList(): List<Cart> {
val response = application.assets.readAssetsFile("response.json")
return GsonBuilder().create().fromJson(response, Array<Cart>::class.java).asList()
}
private fun AssetManager.readAssetsFile(fileName: String): String =
open(fileName).bufferedReader().use { it.readText() }
}
并在创建数据库类时使用dao
将这些项目插入数据库类中,或在"活动"中使用KEY_FIRST_START
将这些项目只填充一次