【发布时间】:2019-08-26 18:34:33
【问题描述】:
要求是解析 json 数据并使用 Kotlin 将其插入到房间数据库中。解析已完成,但是在使用数据类创建表时,由于数据类有一个内部类,问题就出现了。无法使用内部类中的字段创建表。
无法理解如何使用@TypeConverters
@Entity(tableName = "tbl_newsData")
@TypeConverters(ReposPersistentConverter::class)
data class Article(
@PrimaryKey(autoGenerate = true) var _id: Long?,
@ColumnInfo(name = "author") var author: String?,
@ColumnInfo(name = "title") var title: String?,
@ColumnInfo(name = "description") var description: String?,
@ColumnInfo(name = "url") var url: String?,
@ColumnInfo(name = "urlToImage") var urlToImage: String?,
@ColumnInfo(name = "publishedAt") var publishedAt: String?,
@ColumnInfo(name = "content") var content: String?,
var source: Source?
){
constructor() : this(null,"", "", "", "", "",
"", "", "", "",null)
}
class ReposPersistentConverter {
val gson = Gson()
// RepoOwner
@TypeConverter
fun storeRepoOwnerToString(data: Source): String = gson.toJson(data)
@TypeConverter
fun storeStringToRepoOwner(value: String): Source = gson.fromJson(value)
}
@Entity(tableName = "tbl_newsData")
data class Article(
@PrimaryKey(autoGenerate = true) var _id: Long?,
@ColumnInfo(name = "author") var author: String?,
@ColumnInfo(name = "title") var title: String?,
@ColumnInfo(name = "description") var description: String?,
@ColumnInfo(name = "url") var url: String?,
@ColumnInfo(name = "urlToImage") var urlToImage: String?,
@ColumnInfo(name = "publishedAt") var publishedAt: String?,
@ColumnInfo(name = "content") var content: String?,
var source: Source? //inner class
){
constructor() : this(null,"", "", "", "", "",
"", "", "", "",null)
}
////源类
data class Source(
val id: String,
val name: String
)
//json
{
"source": {
"id": null,
"name": "Geeksofdoom.com"
},
"author": "The Movie God",
"title": "Hulu Comings and Goings: What’s New and What’s Leaving In September 2019",
"description": "For those of you who do your entertainment streaming on Hulu, whether it be responsibly in moderation or recklessly in full-on binge watching sessions, there's plenty of TV shows and movies arriving and departing each month to keep track of. The titles set to…",
"url": "https://www.geeksofdoom.com/2019/08/26/hulu-comings-goings-new-leaving-september-2019",
"urlToImage": "https://www.geeksofdoom.com/GoD/img/2016/02/hulu.jpg",
"publishedAt": "2019-08-26T18:00:53Z",
"content": "For those of you who do your entertainment streaming on Hulu, whether it be responsibly in moderation or recklessly in full-on binge watching sessions, there’s plenty of TV shows and movies arriving and departing each month to keep track of.The titles set to … [+8407 chars]"
}
错误:无法弄清楚如何将此字段保存到数据库中。您可以考虑为其添加类型转换器。 私有 com.app.newsapp.dashboard.model.Source 来源;
【问题讨论】:
标签: database kotlin android-room