gson - 使用 GSON 的 Kotlin 对象反序列化

标签 gson kotlin

我有课

class ThreadComment(
    banned: Int,
    closed: Int,
    comment: String?,
    date: String?,
    email: String?,
    files: ArrayList<File>?,
    lasthit: Int,
    name: String?,
    num: String?,
    op: Int,
    parent: String?,
    postsCount: Int,
    sticky: Int,
    subject: String?,
    tags: String?,
    timestamp: Int,
    trip: String?) : Comment(banned, closed, comment, date, email, files, lasthit, name, num, op, parent, postsCount, sticky, subject, tags, timestamp, trip) {

val answers: ArrayList<String> = ArrayList()}

父类看起来像

open class Comment(
    @com.google.gson.annotations.SerializedName("banned")
    val banned: Int = 0,

    @com.google.gson.annotations.SerializedName("closed")
    val closed: Int = 0,

    @com.google.gson.annotations.SerializedName("comment")
    val comment: String? = null,

    @com.google.gson.annotations.SerializedName("date")
    val date: String? = null,

    @com.google.gson.annotations.SerializedName("email")
    val email: String? = null,

    @com.google.gson.annotations.SerializedName("files")
    val files: ArrayList<File>? = null,

    @com.google.gson.annotations.SerializedName("lasthit")
    val lasthit: Int = 0,

    @com.google.gson.annotations.SerializedName("name")
    val name: String? = null,

    @com.google.gson.annotations.SerializedName("num")
    val num: String? = null,

    @com.google.gson.annotations.SerializedName("op")
    val op: Int = 0,

    @com.google.gson.annotations.SerializedName("parent")
    val parent: String? = null,

    @com.google.gson.annotations.SerializedName("posts_count")
    val postsCount: Int = 0,

    @com.google.gson.annotations.SerializedName("sticky")
    val sticky: Int = 0,

    @com.google.gson.annotations.SerializedName("subject")
    val subject: String? = null,

    @com.google.gson.annotations.SerializedName("tags")
    val tags: String? = null,

    @com.google.gson.annotations.SerializedName("timestamp")
    val timestamp: Int = 0,

    @com.google.gson.annotations.SerializedName("trip")
    val trip: String? = null) : Serializable

但是在使用 GSON 反序列化之后,答案字段为空。 Debugger

我也尝试将初始化放入 init{},但它仍然为空,懒惰引发了关于在空对象引用上调用lazy.getValue 的异常

最佳答案

这很奇怪,我只是像在 Java 中一样正常使用 @SerializedName 和一个数据类并且它起作用了:

data class(@SerializedName("my_string_value") val myStringValue: String, @SerializedName("my_int_value") val myIntValue: Int)

关于gson - 使用 GSON 的 Kotlin 对象反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39780021/

相关文章:

java - 将 java Class<> 转换为 kotlin 的 KClass<>

java - 自动记录在 catch block 中,仅当注释异常变量时,对于 Java 或 Kotlin

java - 解析具有未知结构的 JSON 以便与已知结构进行比较的最佳方法?

android - Gson序列化报错类com.activeandroid.DatabaseHelper声明了多个名为mContext的JSON字段

java - gson + json解析错误

java - 如何用Kotlin编写Dagger组件?

java - 卡夫卡只订阅最新消息?

Android Notification - 如何根据模型属性创建系统

java - 如何使用 GSON 从此 JSON 文件获取文本?

java - Gson、Jackson、Flaten Map/HashMap