Hi! I apologize if this has been asked before, but...
# ktor
s
Hi! I apologize if this has been asked before, but is there a good canonical way in ktor to map query params from a GET request to a model class in kotlin? Here’s an example:
Copy code
application.routing {
    get("myroute") {
        val queryParams = call.parameters // the query params from the call
        val paramsMap: Map<String, String> = queryParams.toMap().mapValues { it.value.first() } // I can put them in a map of string fairly easily
        val instanceOfMyClass: MyClass = MyClass(paramsMap["val1"], paramsMap["val2"], etc...) // I have to map them to my class manually each time :(
        // do stuff with the query params
        call.respondJson("your response here.")
    }
}
To be clear, the equivalent of what I’m looking for in spring would look like:
Copy code
import javax.validation.Valid;

@RequestMapping(value = "/getItem", method = RequestMethod.GET)
public ServiceRequest<List<SomeModel>> getClaimStatuses(@Valid RequestParamsModel model) {
    // ...
}
and in JAX-RS it’d use
@BeanParam
https://dennis-xlc.gitbooks.io/restful-java-with-jax-rs-2-0-2rd-edition/en/part1/chapter5/bean_param.html
d
Yes there is! I`ll look it up for you. Just a second.
val myDataClass = call.receive<MyDataClass>()
The feature you are looking for, when I get you right, is the
Content Negotiation Feature
. https://ktor.io/servers/features/content-negotiation.html
s
does that work with query parameters? I’m only finding examples of using it to receive request bodies
and when I do it in my get request it throws
CannotTransformContentToTypeException
. Even with all the values of the class’ constructor (including the nullable ones) passed in.
t
Take a look at the
Locations
feature : https://ktor.io/servers/features/locations.html
💯 1
h
I had done something with objectMapper.convertValue(map, class) in the past, but that was in a different life and I don’t have that code anymore.
k
It's pretty easy to do using gson
👍🏼 1
But, as far as I know, this is the only reason to use
Locations
instead of
Routing
s
yeah the
Locations
feature worked like a charm! Only downside is that it doesn’t allow for multiple different models to be combined in one route
but it works for what I need, and you can always write a wrapper class to abstract if you need to
k
another downside, in my opinion, is that
Locations
removes the path from the routing definition, and you have to keep jumping back to the annotation to view the path
1
no idea why path data isn't parsed just like body data, with something similar to
call.receive<>()