2017-05-22 48 views
1

我是有点困惑了我的科特林类没有按预期工作: 科特林数据类GSON系列化问题

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


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,但我仍然想知道为什么会发生这种情况。

+0

请检查是否有帮助:http://stackoverflow.com/questions/39962284/gson-deserialization-with-kotlin-initializer-block-not-called – hotkey

+0

如果你想让你的构造函数被序列化库正确调用(而不是使用'Unsafe'来实例化它),你可能会对[Moshi]感兴趣(https://medium.com/square-corner-blog/kotlins-a-great-language-for-json-fcd6ef99256b),这在某些方面可以被看作是Gson的继任者。 –

回答

2

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

所有您需要做什么来解决,这是属性更改为一个计算性能:

val isForceUpdate get() = force == 1 

,这样的价值被计算在任何呼叫,而不是存储在一个领域。

+0

谢谢,它的工作原理。 – XieEDeHeiShou