Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

Kotlin Json反序列化后map委托字段异常。如何处理?

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

请问有大神知道如何解决吗?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...