Kotlin Json反序列化后map委托字段异常。如何处理?
fun main(args: Array<String>) {
val json="""
{"content":{
"code":"123"
}}
""".trimIndent()
val gson = Gson()
val msg=gson.fromJson<Msg>(json,Msg::class.java)
println(msg.content["code"])
println(msg.code)
}
class Msg{
val content=HashMap<String,Any?>()
val code:String? by content
}
正常实例没有问题。如果是通过Json反序列化,生成的实例通过委托读取属性就会异常
Exception in thread "main" java.util.NoSuchElementException: Key code is missing in the map.
at kotlin.collections.MapsKt__MapWithDefaultKt.getOrImplicitDefaultNullable(MapWithDefault.kt:24)
反编译代码可知道
@NotNull
private final HashMap content = new HashMap();
@Nullable
private final HashMap code$delegate;
public Msg() {
this.code$delegate = this.content;
}
在默认构造函数,code$delegate有赋值为content
在Maps.kt中
internal inline fun <K, V> Map<K, V>.getOrElseNullable(key: K, defaultValue: () -> V): V {
val value = get(key)
if (value == null && !containsKey(key)) {
return defaultValue()
} else {
@Suppress("UNCHECKED_CAST")
return value as V
}
}
!containsKey(key) 居然为true
请问有大神知道如何解决吗?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…