Open ktoso opened 7 years ago
Comment by levkhomich Sunday Jul 17, 2016 at 04:38 GMT
If request entity is all you need to extract Order
, you are probably looking for FromEntityUnmarshaller
.
Consider this example:
def parseWithJson4s[T](jsonStr: String): T = {
// here goes your json4s logic
parse(jsonStr).camelizeKeys.extract[T]
}
implicit def json4sEntityUnmarshaller[T: Manifest]: FromEntityUnmarshaller[T] = {
Unmarshaller.stringUnmarshaller.map(parseWithJson4s)
}
In most cases, boilerplate provided by Unmarshaller
object is enough.
If you really need to create unmarshaller from HttpRequest
, you can do following:
case class CustomFromRequestUnmarshaller[T](parse: String => T) extends FromRequestUnmarshaller[T] {
override def apply(request: HttpRequest)(implicit ec: ExecutionContext, m: Materializer): Future[T] = {
// here you have access to all parts of request, not just entity
Unmarshaller.stringUnmarshaller(request.entity).map(parse)
}
}
implicit def json4sRequestUnmarshaller = CustomFromRequestUnmarshaller(parseWithJson4s)
Comment by kornelc Sunday Jul 17, 2016 at 13:26 GMT
Thanks for the quick response. That worked. I only needed the string as you said.
Comment by johanandren Monday Jul 18, 2016 at 15:44 GMT
For reference this is the docs for custom unmarshallers: http://doc.akka.io/docs/akka/2.4.8/scala/http/common/unmarshalling.html#custom-unmarshallers
Would be great with a PR with a case class
unmarshaller as you say, probably the most common use case when needing a custom unmarshaller.
Issue by kornelc Saturday Jul 16, 2016 at 22:56 GMT Originally opened as https://github.com/akka/akka/issues/20972
I'm trying to extract a case class with json4s from the entity (form submission) and realized that there are no examples anywhere on how to create these unmarshallers. The doc just has 'implicit val orderUM: FromRequestUnmarshaller[Order] = ???' as an example which doesn't help much unless somebody is already familiar with unmarshallers, which I am not at this point. It would be great to include a case class unmarshalling example in the docs.