I tried to use gson fromJson but i got this print => Countries(countries=null) everytime. what am i missing ?
//CODE
data class Countries(val countries: Map<String, List<String>>)
val jsonString = """
{
"Afghanistan": [
"Herat",
"Kabul",
"Kandahar",
"Molah",
"Rana",
"Shar",
"Sharif",
"Wazir Akbar Khan"
],
"Albania": [
"Elbasan",
"Petran",
"Pogradec",
"Shkoder",
"Tirana",
"Ura Vajgurore"
]
}
""".trimIndent()
val countries = Gson().fromJson(jsonString, Countries::class.java)
println(countries)
2
Answers
It couldn’t find the
countries
key. There are basically 3 options here.Alternatively, you can change an entity you deserialize to (e.g. use
object : TypeToken<Map<String, List<String>>>() {}.type
as the second parameter).Another option is to create a custom deserializer for your existing json and
Countries
class as follows:And use
GsonBuilder().registerTypeAdapter(Countries::class.java, countriesDeserializer).create()
instead of simplyGson()
To determine type
Gson parse