How do I deserialize a JSON response when making a http request in akka?

536 Views Asked by At
import spray.json._
import DefaultJsonProtocol._

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

I am making a http request:

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")
    }

How do I use the response in the success scenerio and deserialize to my case class for User?

1

There are 1 best solutions below

0
yǝsʞǝla On BEST ANSWER
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]