Search code examples
jsonkotlingson

How to describe JSON list with data classes in Kotlin / gson


I want to parse the JSON from nominatim from OpenStreetMap.

Example

It's a list and I don't have a clue how I can describe the list. I am using Gson, these is my data class:

data class Destination(
    val lat: Double,
    val lon: Double,
    val display_name: String
)

and this is my Gson implementation:

val list = Gson().fromJson<List<Destination>>(
    body,
    Destination::class.java
)

It gives me this error:

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

But I declared an Array in my Gson implementation. Anyone having an idea how to fix this?


Solution

  • I figured it out, you have to use an Array, not a List:

    val list : Array<Destination> = Gson().fromJson(
        body,
        Array<Destination>::class.java
    )