我从休息服务接收到json,该服务由一些人组成,每个人都有引用某些技能的ID列表,每个人都有引用某些技能类型的ID列表:
{
"person": [{
"id": 1,
"name": "Biatrix",
"age": 29,
"skillIndices": [
1,
2
]
},
{
"id": 2,
"name": "Oren",
"age": 27,
"skillIndices": [
1,
2
]
},
{
"id": 3,
"name": "Bill",
"age": 52,
"skillIndices": [
1,
2
]
}
],
"skill": [{
"id": 1,
"name": "Sword",
"typeIndices": [
1,
2
]
},
{
"id": 2,
"name": "Kong fu",
"typeIndices": [
3,
4
]
}
],
"type": [{
"id": 1,
"name": "Hattori"
},
{
"id": 2,
"name": "Hanzō"
},
{
"id": 3,
"name": "Shaolin"
},
{
"id": 4,
"name": "Tai Chi Quan"
}
]
}
为了将这些数据持久存储到Room数据库中,我具有三个实体和三个dao。
我需要以某种方式将id转换为真实对象,以便在使用存储库将数据作为LiveData检索时我会得到类似的东西,可以在我的UI中使用:
{
"person": [{
"id": 1,
"name": "Biatrix",
"age": 29,
"skills": [
[{
"id": 1,
"name": "Sword",
"types": [
"Hattori",
"Hanzō"
]
},
{
"id": 2,
"name": "Kong fu",
"types": [
"Shaolin",
"Tai Chi Quan"
]
}
]
},
{
"id": 2,
"name": "Oren",
"age": 27,
"skills": [
[{
"id": 1,
"name": "Sword",
"types": [
"Hattori",
"Hanzō"
]
},
{
"id": 2,
"name": "Kong fu",
"types": [
"Shaolin",
"Tai Chi Quan"
]
}
]
},
{
"id": 3,
"name": "Bill",
"age": 52,
"skills": [
[{
"id": 1,
"name": "Sword",
"types": [
"Hattori",
"Hanzō"
]
},
{
"id": 2,
"name": "Kong fu",
"types": [
"Shaolin",
"Tai Chi Quan"
]
}
]
}
]
}
这当然需要(?)作为Pojo在Entity类下发生,对吗?尝试使用@Relation
注释来做到这一点,但似乎无法理解该怎么做。
这里是Person
的实体:
package com.myapp.data.db.entity
import androidx.room.*
@Entity(tableName = "person")
data class Person(
@PrimaryKey(autoGenerate = false)
var id: Int = 0,
var name: String = 0,
var age: Int = 0,
var skillIndices: List<Int> = arrayListOf()
)
我该如何操作该实体,以便在请求Person
数据时得到类似上面(第二个)数据集的信息?
答案 0 :(得分:2)
skillIndices
应该是它自己的内部实体,以便您可以在var skillIndices: List<Skill>
中引用Person
。
也不要忘记@SerializeName("skill")
字段skillIndices
,因为它没有相同的名称。
@Entity(tableName = "person")
data class Person(
@PrimaryKey(autoGenerate = false)
var id: Int = 0,
var name: String = 0,
var age: Int = 0,
var skills: List<Skill> = arrayListOf()
)
@Entity(tableName = "skill")
data class Skill(
@PrimaryKey(autoGenerate = false)
var id: Int = 0,
var name: String = 0,
var types: List<String> = arrayListOf()
)