简体   繁体   中英

How does Gson.fromJson method succeeded to parse a Json string although TypeToken isn't suit to parsed String?

I have a code that I can't understand why it isn't throwing a run time exception . Here is a Json String that I'm trying to convert to Map<String, Any>, but some of the keys are from Int type and not a String . The code:

    val json = """{1: "Kotlin Tutorial", "2": "bezkoder", "3" : ["Kotlin","Basic"]}"""
    val gson = Gson()

    var tutorialMap: Map<Int, Any> = gson.fromJson(json, object : TypeToken<Map<Int, Any>>() {}.type)
    tutorialMap.forEach { Log.e("dadffas",it.toString()) }

As you can see keys: 1,3 are from Int type. What happen here? some kind of boxing? In addition if I declare the TypeToken as Map<Int,Any> code is still being compiled? Again kind of boxing (behind the scene String.toInt method is running)?

Gson's approach is, to come from the Java/Kotlin side and try to coerce the Json value into the type that is expected on Java side. So, as the type of the keys of your map is Integer, it tries to coerce what it gets from Json to Integer.

You need to be aware that your whole Json initally is just a string to Gson. It gets tokenized but is still a bunch of strings until in the end Gson sees you want a certain string as an Integer. And it ia clever enough to turn 2 and "2" into an integer.

If your json would have a key like "foo" , you'd get an exception.

PS: If you're really interested you can use the debugger and step into the fromJson() method and see exactly how its done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM