How can I spray an unmarshall list in query parameters

I am new to spray. I play around with building routes, and while I can get the parameters from the query string using the parameter directive, I am having problems when I want one of the parameters to be a list.

In this example, I defined this case class:

case class Person(name: String, friends: Int) 

Currently my route is as follows:

 path("test") { get { parameters('name, 'friend ).as(Person) { p => complete(p) } } } 

this works fine and i can do get: localhost: 8080 / test? name = jo & friends = 12 and get what I expect.

I want to pass the ids friends list, not just the number of friends, so I started by changing the case class as follows:

 case class Person(name: String, friends: Array[Int]) 

and my call: localhost: 8080 / test? name = jo & friends = 1,2

it does not compile. I get a type mismatch: found: Person.type required: spray.routing.HListDeserializer [formless. :: [String, formless. :: [String, shapeless.HNil]],] get {parameters ('name,' friend). as (Person) {p => ^ comment: this points to P in .as (Person)

Any idea what I'm doing wrong? I would like an answer on how to do this. It would be even better to explain what kind of shapeless type he is looking for. Thanks

+5
source share
1 answer

The first example worked because the 'friend parameter could be automatically converted from String to Int , therefore, satisfying the requirements of the case Person class.

The latter does not work because there is no conversion available String => Array[Int] , so it is impossible to materialize Person from two strings.

You can say that it treats both 'friend and 'name as strings, looking at the message error

 spray.routing.HListDeserializer[shapeless.::[String,shapeless.::[String,shapeless.HNil]],?] 

can be simplified to something like

 String :: String :: HNil 

i.e. he is looking for something that can deserialize two strings into something else.

On the bottom line, you will need to create a custom deserializer to parse "1,2" into Array[Int] .

Here's the relevant documentation: http://spray.io/documentation/1.1-SNAPSHOT/spray-httpx/unmarshalling/#unmarshalling

+4
source

Source: https://habr.com/ru/post/1203648/


All Articles