在akka中发出http请求时,如何反序列化JSON响应?

x6h2sr28  于 2022-11-05  发布在  其他
关注(0)|答案(1)|浏览(155)
import spray.json._
import DefaultJsonProtocol._

case class User(id: String, name: String)

我正在发出http请求:

val responseFuture: Future[HttpResponse] =
    Http().singleRequest(
      HttpRequest(uri =
        s"https://example.com/get/user.json"
      )
    )

  responseFuture
    .onComplete {
      case Success(res) => res.
      case Failure(_)   => sys.error("something wrong")
    }

如何在成功场景中使用响应并反序列化到User的case类?

c0vxltue

c0vxltue1#

import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._

case class User(id: String, name: String)

// define implicit converter between json and case class with 2 fields
implicit val userFormat = jsonFormat2(User)

val user: Future[User] = Unmarshal(responseFuture).to[User]

相关问题