https://kotlinlang.org logo
#ktor
Title
# ktor
s

sonofblip

07/11/2019, 3:35 PM
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

Dennis Schröder

07/11/2019, 3:37 PM
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

sonofblip

07/11/2019, 4:04 PM
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

tseisel

07/11/2019, 4:58 PM
Take a look at the
Locations
feature : https://ktor.io/servers/features/locations.html
💯 1
h

halley

07/11/2019, 5:27 PM
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

Kevin Schmeichel

07/11/2019, 5:35 PM
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

sonofblip

07/11/2019, 5:49 PM
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

Kevin Schmeichel

07/11/2019, 5:57 PM
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<>()
15 Views