在Android Room数据库中存储List <Object>

时间:2019-07-04 23:37:46

标签: java android kotlin retrofit2 android-room

我目前正在使用RetroFit从Web检索JSON对象,我得到的JSON对象实际上是对象列表。我想将该列表存储到Room数据库表中。

interface currentNewsService {
    @GET("api/feed")
    fun getFeed(
            @Query("amount") amount: Int,
    ): Deferred<currentNewsResponse>

    companion object{

        operator fun invoke(): currentNewsService {

            val okHttpClient = OkHttpClient.Builder().build()
            return Retrofit.Builder().client(okHttpClient)
                    .baseUrl("https://someUrl")
                    .addCallAdapterFactory(CoroutineCallAdapterFactory())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build().create(currentNewsService::class.java)
        }
    }
}

然后我创建了一个数据类,该类使我可以访问RetroFit调用的响应。我从网络上收到响应,但是在将对象列表存储在房间中时遇到问题。

data class currentNewsResponse(
        val news: List<News>){
}

这是我在会议室中创建的表的示例:

@Entity(tableName = "news", indices = [Index(value = ["newsId"], unique = true)])
data class Feed(
@PrimaryKey
val id: Int
@SerializedName("current_news_id")
val newsId: Int)

谁能给我指出任何相关文档,或者通过给我一个示例来说明如何存储对象列表来帮助我?

1 个答案:

答案 0 :(得分:1)

Room不允许您直接存储List个对象。

您正在寻找的答案是TypeConverter,通过它您可以将对象列表转换为Room允许的类型,并在查询时转换回对象列表。

您已经使用Gson。因此,请在Gson内部使用TypeConverter对数据进行序列化/反序列化。

关于如何做到这一点的教程太多了。