jsonscalaakkahttpentity

Fetch the json from HttpEntity


I have an object of akka.http.scaladsl.model.HttpEntity looking like HttpEntity("application/json", {Myjson here})

Is there a way i can fetch my json from the entity without any string manipulations(other than converting to a string and doing a split)


Solution

  • You will need a JSON parser and a glue code between the JSON parser and Akka Http called Unmarshaller.

    Akka Http includes unmarshallers for spray-json library. You can find more unmarshallers in hseeberger/akka-http-json library.

    If you choose to use spray-json a pseudo code for that would be

    case class MyJson(v1: String, v2: Int)
    
    object JsonProtocol extends DefaultJsonProtocol {
      implicit val myFormat = jsonFormat2(MyJson)
    }
    
    val resp: Future[MyJson] = Unmarshal(response).to[MyJson]