找不到类型为akka.http.scaladsl.model.HttpResponse的Json序列化程序。尝试为此类型实现隐式写入或格式

时间:2018-05-02 03:18:00

标签: scala playframework

我在播放控制器中使用以下代码

class MyController @Inject()(cc: ControllerComponents, actorSystem: ActorSystem)(implicit exec: ExecutionContext) extends AbstractController(cc) {


  val logger: Logger = Logger(this.getClass())

def mypost = Action.async(parse.json) {
  request =>
    val item = request.body.validate[Myrequest]
    val req=request.body.as[Myrequest]
    implicit val system: ActorSystem = ActorSystem()
    implicit val materializer: ActorMaterializer = ActorMaterializer()
    implicit val executionContext: ExecutionContextExecutor = system.dispatcher



        val responseFuture: Future[HttpResponse] = Http().singleRequest(HttpRequest(uri = "http://akka.io"))


        responseFuture.map {
          case response @ HttpResponse(StatusCodes.OK, _, _, _) =>
            val setCookies = response.headers
            println(s"Cookies set by a server: $setCookies")
            Ok(Json.toJson(response))
          case _ => sys.error("something wrong")
        }




}
}

调用此控制器时出现以下错误

No Json serializer found for type akka.http.scaladsl.model.HttpResponse. Try to implement an implicit Writes or Format for this type.

我已经尝试在Json中返回响应体而不是整个HttpResponse,如下所示

Ok(Json.toJson(response.entity.dataBytes.runWith(Sink.fold(ByteString.empty)(_ ++ )).map(.utf8String) map { result => Json.parse(result) }))

它抛出错误

"No Json serializer found for type scala.concurrent.Future[play.api.libs.json.JsValue]. Try to implement an implicit Writes or Format for this type. " –

或者我应该使用任何其他HttpClient?

1 个答案:

答案 0 :(得分:0)

就像错误消息所示,如果您想将整个HttpResponse对象放在正文中,则需要为其定义Writes

如果您只想传递响应正文,并且响应正文已经定义了一个Writes,例如Json(JsValue)或String,然后您可以从HttpResponse中提取该内容,然后返回Ok(responseBody)