Field 'age2' can only be read from 'application/x-www-form-urlencoded' form content

StackOverflow https://stackoverflow.com/questions/16533763

  •  29-05-2022
  •  | 
  •  

Question

Could you guys tell me why following form of extraction works for both multipart/form-data and x-www-form-urlencoded requests

formFields("firstName"?, "age2"?, "sex", "vip"?) {
  (firstName : Option[String], age2, sex, vip) =>
    complete(firstName + "." + age2 + "." + sex + "." + vip)
}

but this, seemingly equal, version of code

formFields('firstName :: ("age2".as[Int]) :: ('sex?) :: ("VIP" ? false) :: HNil) {
  (firstName : String, age2 : Int, sex : Option[String], vip : Boolean) =>
    complete(firstName + "." + age2 + "." + sex + "." + vip)
}

doesn't work when request is multipart/form-data encoded.

Server returns following error:

There was a problem with the requests Content-Type:
Field 'age2' can only be read from 'application/x-www-form-urlencoded' form content

I see a call-stack to spray.httpx.unmarshalling.FormField.fail but my Scala skills are not strong enough to decipher it.

Était-ce utile?

La solution

"Implementing a default unmarshaler for int" can be done like this:

object JsonImplicits extends DefaultJsonProtocol {
    implicit val IntUnmarshaller = Unmarshaller.delegate[String, Int](MediaRanges.`*/*`) { _.toInt }
}

And making sure its in scope before your route definition by adding the import right before: import JsonImplicits._

Autres conseils

Turned out there is no default unmarshaler for Int. So if you implement one it all works.

Not sure why it wasn't done by maintainers in the first place.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top