如何使用 Room ORM 缓存此响应?

How to cache this response using Room ORM?

这是我的 json 结构的 link。我想使用 Room ORM 缓存它。所以我在下面写了一些代码。但是当我渲染我的屏幕时,我注意到每个部分只有一个嵌套项。如您所见,每个部分中应该有多个嵌套项。我无法坚持 objects array

这是Entities

的代码
@Entity(tableName = "calendar")
data class Calendar(
    @PrimaryKey val id: String,
    @ColumnInfo(name = "title") var title: String,
    @ColumnInfo(name = "start_time") var startTime: Long,
    @ColumnInfo(name = "end_time") var endTime: Long,
)


@Entity(tableName = "inspection_object",
    foreignKeys = [
        ForeignKey(
            parentColumns = ["id"],
            childColumns = ["calendar_id"],
            entity = Calendar::class,
            onDelete = ForeignKey.CASCADE,
            onUpdate = ForeignKey.CASCADE
        )
    ],
)
data class InspectionObj(
    @PrimaryKey val id: String,
    @ColumnInfo(name = "calendar_id") val calendarId: String,
    @ColumnInfo(name = "title") val title: String,
    @ColumnInfo(name = "address") val address: String,
    @ColumnInfo(name = "time") val time: Long,
    @ColumnInfo(name = "total_tasks") val totalTasks: Int,
    @ColumnInfo(name = "is_today") val isToday: Boolean,
    @ColumnInfo(name = "is_expired") val isExpired: Boolean,
    @ColumnInfo(name = "completed_tasks") val completedTasks: Int
)


data class CalendarWithObjects(
    @Embedded
    val calendar: Calendar,

    @Relation(parentColumn = "id", entityColumn = "calendar_id", entity = InspectionObj::class)
    val objects: List<InspectionObj>
)

这是一个

@Dao
abstract class CalendarDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    abstract fun saveCalendar(calendar: Calendar)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    abstract fun saveInspectionObject(inspectionObj: InspectionObj)

    @Query("delete from calendar")
    abstract fun deleteFromCalendar()

    @Query("delete from inspection_object")
    abstract fun deleteFromInspectionObject()

    @Transaction
    open fun insertCalendar(calendar: Calendar, inspectionObj: InspectionObj) {
        saveCalendar(calendar)
        saveInspectionObject(inspectionObj)
    }

    @Query("select count(*) from calendar")
    abstract fun selectCalendarRowsCount(): Int

    @Query("select * from calendar")
    abstract fun selectCalendarWithObjects(): List<CalendarWithObjects>
}

I can't persist objects array

为此,您需要持久保存 list/array 个对象的方法。你有这个:

@Insert(onConflict = OnConflictStrategy.REPLACE)
fun saveInspectionObject(inspectionObj: InspectionObj)

看来你需要这个:

@Insert(onConflict = OnConflictStrategy.REPLACE)
fun saveInspectionObjectList(inspectionObjList: List<InspectionObj>) // or inspectionObjList: Array<InspectionObj>

您甚至可以使用下一个选项来保留 CalendarinspectionObjList:

@Insert(onConflict = OnConflictStrategy.REPLACE)
fun saveCalendarAndInspectionObjectList(calendar: Calendar, inspectionObjList: List<InspectionObj>)