【问题标题】:How to Persist JSON object with JSON array inside it using Room and moshi with Kotlin如何使用带有 Kotlin 的 Room 和 moshi 持久化带有 JSON 数组的 JSON 对象
【发布时间】:2020-04-07 16:04:38
【问题描述】:

所以,我有这个 JSON 对象

{ 
"name": "News",
"infos":[
   { "title":"hello",
     "content":"this is the content",
     "recent":true
   },
   { "title":"Tax",
     "content":"The European Commission is considering possible tax benefits",
     "recent":true
   },
   { "title":"Tax",
     "content":"The European Commission is considering possible tax benefits",
   }
]

我需要将这个对象与 Room(Android) 一起使用 moshi 来反序列化到我的数据类中

@JsonClass(generateAdapter = true)
@Entity(
    tableName = "news"
)

data class News(
    @ColumnInfo(name = "name")
    val name:String = "News",

    val infos:List<Info>,

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id")
    val id: Int){
}

@JsonClass(generateAdapter = true)
@Entity(tableName = "info",
    foreignKeys = [
        ForeignKey(entity = News::class, parentColumns = ["id"], childColumns = ["info_id"])
    ],
    indices = [Index("info_id")])
data class Info(
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "id")
    var id: Int,
    val title : String,
    val content: String,
    val recent: Boolean?,
    @ColumnInfo(name = "info_id")
    val infoId: Int) {

}

我还创建了 Roomd 数据库和我的 @dao 类 @Insert 乐趣。但我得到这个错误:

error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.
    private final java.util.List<com.example.data.Info> infos = null;

【问题讨论】:

    标签: android json kotlin android-room moshi


    【解决方案1】:

    您缺少 TypeConverters。 Room 无法保存复杂的字段类型,如列表、日期、数组等。

    请参考: https://developer.android.com/training/data-storage/room/referencing-data

    【讨论】:

    • 欢迎来到 SO!请阅读tourHow do I write a good answer?请考虑添加代码以使您的答案更清晰
    • 当然,谢谢。关于这个主题有很多可用的答案。我猜这个问题应该结束了。
    • 如果您发现重复,您可以标记此问题,该问题将投票关闭为重复。
    猜你喜欢
    • 1970-01-01
    • 2023-02-15
    • 2016-01-21
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多