【发布时间】: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 ???
然后我尝试了lateinit 或by lazy{},仍然不行。
那么,我该怎么办..我现在直接使用info.force==1,但我仍然想知道为什么会发生这种情况。
【问题讨论】:
-
请检查这是否有帮助:stackoverflow.com/questions/39962284/…
-
如果你希望你的构造函数被序列化库正确调用(而不是使用
Unsafe来实例化它),你可能对Moshi感兴趣,在某些方面可以看作是Gson 的继任者。
标签: int boolean gson kotlin data-class