【问题标题】:Kotlin data class Gson serialization issueKotlin 数据类 Gson 序列化问题
【发布时间】:2017-10-21 18:19:00
【问题描述】:

我有点困惑,因为我的 kotlin 课程没有按预期工作:

用于检查更新信息的数据类:

data class UpdateInfo constructor(//kotlin class
    val description: String,
    val force: Int,
    val platform: String,
    val title: String,
    val url: String,
    @SerializedName("version")
    val versionCode: Int = 0
) : Serializable {
    val isForceUpdate = force == 1
}

也是一个用来解码对象形式json的工具:

public class JsonUtil {//java class
    private static final Gson gson;
    static {
        BooleanAdapter booleanAdapter = new BooleanAdapter();
        gson = new GsonBuilder()
            .serializeNulls()
            .disableHtmlEscaping()
            .setLenient()
            .registerTypeAdapter(Boolean.class, booleanAdapter)
            .registerTypeAdapter(boolean.class, booleanAdapter)
            .create();
    }
}

当我测试它时:

val json = "{\"force\"=\"1\"}"
val info = JsonUtil.fromJsonObject(json, UpdateInfo::class.java)
println(info)
println(info.force == 1)
println(info.isForceUpdate)

我明白了:

UpdateInfo(description=null, force=1, platform=null, title=null, url=null,versionCode=0)
true
false

什么? info.isForceUpdate = false ???
然后我尝试了lateinitby lazy{},仍然不行。 那么,我该怎么办..我现在直接使用info.force==1,但我仍然想知道为什么会发生这种情况。

【问题讨论】:

  • 请检查这是否有帮助:stackoverflow.com/questions/39962284/…
  • 如果你希望你的构造函数被序列化库正确调用(而不是使用Unsafe来实例化它),你可能对Moshi感兴趣,在某些方面可以看作是Gson 的继任者。

标签: int boolean gson kotlin data-class


【解决方案1】:

问题是属性val isForceUpdate = force == 1 在类的实例化时计算一次,然后存储在一个字段中。因为 Gson 使用Unsafe 来实例化类,所以该字段设置为其默认值false

解决此问题所需要做的就是将属性更改为计算属性:

val isForceUpdate get() = force == 1

以便在任何调用时计算该值,而不是存储在字段中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 1970-01-01
    相关资源
    最近更新 更多