Search code examples
jsonkotlinktorkotlin-multiplatform

How do I parse a response with Ktor


I'm trying to do a Get call with Ktor in a multiplatform project. This is the code:

private val client = HttpClient()

fun myCall(callback: (List<Film>) -> Unit) {

    viewModelScope.launch {
        val result:List<Film> = client.get {
            url("https://data.sfgov.org/resource/wwmu-gmzc.json")
        }
        callback(result)
    }
}

Every time I make this request the application closes and I don't receive any message that gives me a clue what's going on. If instead of putting a list Film as the result type I put String then it works and I receive a list of movies, but I want to parse it to my own objects and I am unable.

Is there something wrong with the call?


Solution

  • For the Ktor http client to deserialize to your custom object, you would need to install JsonFeature while creating your http client, which would need the io.ktor:ktor-client-json dependency added.

    val client = HttpClient {
       install(JsonFeature)
    }
    

    Then depending on whichever serializer you want to use (Ktor supports Gson, Jackson and Kotlinx.Serialization), you need to add the dependency of the respective serializer. For eg, if you want to use Gson, you need to add the dependency for io.ktor:ktor-client-gson. Then your API response would get deserialized to your List<Film> object.

    val result: List<Film> = client.get {
       url("https://data.sfgov.org/resource/wwmu-gmzc.json")
    }
    

    More on the above in the Ktor documentation