[英]How to unmarshall akka http request entity as string?
我正在尝试将请求有效内容解编为字符串,但是由于某种原因它失败了。 我的代码:
path("mypath") {
post {
decodeRequest {
entity(as[String]) {jsonStr => //could not find implicit value for...FromRequestUnmarshaller[String]
complete {
val json: JsObject = Json.parse(jsonStr).as[JsObject]
val jsObjectFuture: Future[JsObject] = MyDatabase.addListItem(json)
jsObjectFuture.map(_.as[String])
}
}
}
}
}
例如,在此SO线程中,似乎默认情况下应使用此隐式。 但是也许在akka-http中是不同的吗?
我尝试导入akka.http.scaladsl.unmarshalling.PredefinedFromEntityUnmarshallers
,它具有一个stringUnmarshaller
但没有帮助。 可能是因为这返回的类型FromEntityUnmarshaller[String]
而是FromRequestUnmarshaller[String]
。 spray.httpx.unmarshalling.BasicUnmarshallers
还有一个字符串解组器spray.httpx.unmarshalling.BasicUnmarshallers
但这也无济于事, akka.http.scaladsl.unmarshalling.PredefinedFromStringUnmarshallers
如何解组(和编组)为字符串?
(奖金:如何直接在JsObject中解编组(播放json)。但是也只有字符串,因为我对为什么这样做不起作用感兴趣,并且在其他情况下可能很有用)。
使用1.0-RC3
谢谢。
只要您在范围内具有正确的隐式,您的代码就可以了。 如果您在作用域中具有隐式FlowMaterializer
,则应按预期运行,如编译的代码所示:
import akka.http.scaladsl.server.Route
import akka.actor.ActorSystem
import akka.stream.ActorFlowMaterializer
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.stream.FlowMaterializer
implicit val system = ActorSystem("test")
implicit val mater = ActorFlowMaterializer()
val routes:Route = {
post{
decodeRequest{
entity(as[String]){ str =>
complete(OK, str)
}
}
}
}
如果您想更进一步,并JsObject
对JsObject
编组, JsObject
需要作用域中的隐式Unmarshaller
即可处理该转换,如下所示:
implicit val system = ActorSystem("test")
implicit val mater = ActorFlowMaterializer()
import akka.http.scaladsl.unmarshalling.Unmarshaller
import akka.http.scaladsl.model.HttpEntity
implicit val um:Unmarshaller[HttpEntity, JsObject] = {
Unmarshaller.byteStringUnmarshaller.mapWithCharset { (data, charset) =>
Json.parse(data.toArray).as[JsObject]
}
}
val routes:Route = {
post{
decodeRequest{
entity(as[String]){ str =>
complete(OK, str)
}
}
} ~
(post & path("/foo/baz") & entity(as[JsObject])){ baz =>
complete(OK, baz.toString)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.