skip to Main Content

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


  1. It couldn’t find the countries key. There are basically 3 options here.

    1. You can modify json itself:
    val jsonString = """
    {
      "countries": {
        "Afghanistan": [
          "Herat",
          "Kabul",
          "Kandahar",
          "Molah",
          "Rana",
          "Shar",
          "Sharif",
          "Wazir Akbar Khan"
        ],
        "Albania": [
          "Elbasan",
          "Petran",
          "Pogradec",
          "Shkoder",
          "Tirana",
          "Ura Vajgurore"
        ]
      }
    }
    """.trimIndent()
    
    1. Alternatively, you can change an entity you deserialize to (e.g. use object : TypeToken<Map<String, List<String>>>() {}.type as the second parameter).

    2. Another option is to create a custom deserializer for your existing json and Countries class as follows:

    val countriesDeserializer =
        JsonDeserializer { json, _, context ->
            Countries(
                context.deserialize(json, object : TypeToken<Map<String, List<String>>>() {}.type)
            )
        }
    

    And use GsonBuilder().registerTypeAdapter(Countries::class.java, countriesDeserializer).create() instead of simply Gson()

    Login or Signup to reply.
  2. To determine type

    val countryCityType = object : TypeToken<Map<String, List<String>>>() {}.type
    

    Gson parse

    val countryCityData: Map<String, List<String>> = Gson().fromJson(jsonString, countryCityType)
    
    println(countryCityData)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search