0

I get a Json feed back from a remote third party API in this way:

val myjson: Future[HttpResponse] = http.singleRequest(HttpRequest(uri = encodedUri))

myjson onComplete {
   case Success(response) => sender ! WrappedResponse(response.entity.toJson)
   case Failure...
}

case class WrappedResponse(response: JsValue)

The HttpResponse.entity contains my json feed. Is it possible marshall and unmarshall this Json feed or only parts of it?

One of the problem is that when I send it back wrapped the json in a case class I get something:

Error:(38, 78) Cannot find JsonWriter or JsonFormat type class for akka.http.scaladsl.model.ResponseEntity
        case Success(response) => sender ! WrappedResponse(response.entity.toJson)

How can I "marshall" Json itself?

UPDATE

I finally get to unmarshall the data first in this way:

val responseData = sendHttpRequest(encodedUrl)
      val bodyAsString = responseData.flatMap { response => Unmarshal(response.entity).to[String] }

      bodyAsString onComplete {
        case Success(body) => sender ! WrappedResponse(body)
        case Failure(response) => response
      }

and in my marshaller:

trait MyJsonMarshaller extends SprayJsonSupport with DefaultJsonProtocol {

  implicit val titleDeedResponseFormat = jsonFormat1(WrappedResponse.apply)

}

but the "re-apply" marshalling is not working

Randomize
  • 8,651
  • 18
  • 78
  • 133

1 Answers1

0

Sure! This is untested and adapted from code in my own project, but you could do something like:

import akka.http.scaladsl.unmarshalling.Unmarshal

val myResponse: Future[HttpResponse] = http.singleRequest(HttpRequest(uri = encodedUri))

val jsonFut = myResponse.flatMap {
   case HttpResponse(StatusCodes.OK, _, entity, _) =>
     Unmarshal(entity).to[JsObject]
   case other =>
     logger.debug(s"Failed response: $other")
     throw new Exception(other.toString())
}.recover {
  // ... error handling
}

In this case, you would deal with the JsObject result in an ad hoc way. But if you define JsonFormat instances for domain model classes, you could unmarshall directly to domain objects.

acjay
  • 34,571
  • 6
  • 57
  • 100