Ixx*_*Ixx 13 json scala akka-http
我正在尝试将请求有效负载解组为字符串,但由于某种原因它失败了.我的代码:
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])
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
例如,在这个SO线程中,似乎默认情况下这个隐式应该是可用的.但也许这在akka-http中有所不同?
我尝试导入akka.http.scaladsl.unmarshalling.PredefinedFromEntityUnmarshallers
哪一个stringUnmarshaller
但它没有帮助.也许因为这FromEntityUnmarshaller[String]
不会返回类型FromRequestUnmarshaller[String]
.还有一个字符串unmarshaller,spray.httpx.unmarshalling.BasicUnmarshallers
但这也没有帮助akka.http.scaladsl.unmarshalling.PredefinedFromStringUnmarshallers
我如何解组(和编组)成一个字符串?
(Bonus:如何直接在JsObject中解组(播放json).但也只是字符串,因为我对它为什么不起作用感兴趣,并且它可能对其他情况有用).
使用1.0-RC3
谢谢.
cmb*_*ter 17
只要您在范围内有正确的含义,您的代码就可以了.如果你有一个隐含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)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果你想更进一步然后解组,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)
}
}
Run Code Online (Sandbox Code Playgroud)