在 akka 中发出 http 请求时如何反序列化 JSON 响应?
How do I deserialize a JSON response when making a http request in akka?
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")
}
如何使用成功场景中的响应并反序列化到我的案例 class for User
?
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]
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")
}
如何使用成功场景中的响应并反序列化到我的案例 class for User
?
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]