https://kotlinlang.org logo
Title
r

Rui

09/29/2020, 2:37 PM
Hi, I was trying to get parameters from a request body by using
call.receive<Parameters>()
and got:
Unable to invoke no-args constructor for interface io.ktor.http.Parameters. Registering an InstanceCreator with Gson for this type may fix this problem
Any ideas?
d

Dominik wuttke

09/29/2020, 3:58 PM
Your server doesn't know what type of data are you receiving and what it should do with it. Installing a contentnegotiator like Gson for example tells your server what it should do with received data of a specific type. For example this
install(ContentNegotiation) {
    gson {
        setDateFormat(DateFormat.LONG)
        setPrettyPrinting()
        register(ContentType.Text.Plain, GsonConverter(GsonBuilder().create()))

    }
}
For received data with a ContentType of plain text, the received data will be converted with the GsonConverter. In my example I am calling
call.receive<FormMessage>()
at a later stage, FormMessage is a JSONObject from this class
data class FormMessage(val name: String, val email : String, val message: String)
r

Rustam Siniukov

09/29/2020, 4:23 PM
Gson
doesn’t know how to create
Parameters
instance, because it is an interface. You can create class that will represent request body or use
Map<String, Any>
r

Rui

09/29/2020, 6:04 PM
@Rustam Siniukov thanks for your reply. After I change Parameters to Map<String, String>, it works now. Funny that I saw several examples that they simply use call.receive<Parameters>() and it worked for them. Kinda wonder why does that happen.
@Dominik wuttke Thanks for your reply. I did add a gson ContentNegotiation as you recommended (with or without "register" line), but still no luck here. My request body is quite simple, only contains String->String and String-> Gson.toJson(Obj). Not sure what was missing here.
r

Rustam Siniukov

09/30/2020, 7:58 AM
@Rui
receive<Parameters>()
should work when your content type is
multipart/form-data
or
application/x-www-form-urlencoded