Hi, I was trying to get parameters from a request ...
# ktor
r
Hi, I was trying to get parameters from a request body by using
Copy code
call.receive<Parameters>()
and got:
Copy code
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
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
Copy code
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
Copy code
call.receive<FormMessage>()
at a later stage, FormMessage is a JSONObject from this class
Copy code
data class FormMessage(val name: String, val email : String, val message: String)
r
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
@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
@Rui
receive<Parameters>()
should work when your content type is
multipart/form-data
or
application/x-www-form-urlencoded