0

First time i am using Ktor in my android project I am not getting response from server, my requirement is to make a POST request with JSON in body

request format of JSON as

{
   "country": "Malaysia"
}

I tried on postman it is working fine, but not working with Ktor client

I am trying to make json from a hashMap, but I am unable to create a JSON like structure

here is my code

 override suspend fun getFlag(url: String, query: MutableMap<String, String>): FlagResponse {

    Log.d("Flag Requested", "getFlag: $query")
    return client.post(URL)
    {
        contentType(ContentType.Application.Json)
        body = Json.encodeToJsonElement(query.toMap().toString())
    }
}

 Error Log : 

 kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at 
 offset 1: Expected string literal with quotes.
W/System.err: Use 'isLenient = true' in 'Json {}` builder to accept non-compliant 
JSON.
 W/System.err: JSON input: {country=Philippines}
Jitendra Prajapati
  • 1,002
  • 1
  • 10
  • 33

1 Answers1

0

I able to achieve this by using a data class, like

    @kotlinx.serialization.Serializable
    data class Param(val country: String)

    return client.post(URL)
    {
        contentType(ContentType.Application.Json)
        setBody(body = Param(query))
    }.body()
Jitendra Prajapati
  • 1,002
  • 1
  • 10
  • 33