1

I do a GET HTTP call to a rest service which returns a json. I would like to parse the json to a scala object but here I got stuck. I am using the Akka api and I can't manage to retrieve the content from the Akka's ResponseEntity

Here is my sbt file:

name := "ScalaHttp"

version := "1.0"

scalaVersion := "2.11.8"

libraryDependencies ++={
  val akkaV = "2.4.5"
  Seq(
    "com.typesafe.akka"         %%  "akka-http-core"    % akkaV,
    "com.typesafe.play"         %%  "play-json"         % "2.4.0-M3"
  )
}

And here is the app

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpRequest
import akka.stream.ActorMaterializer

import scala.concurrent.ExecutionContext.Implicits.global


object Sender {
  def main(args: Array[String]): Unit = {

    implicit val system = ActorSystem()
    implicit val materializer = ActorMaterializer()

    Http().singleRequest(HttpRequest(uri = "http://declinators.com/declinator?noun=komunikacja")) foreach {
      y => println(y.entity)
        println(y.entity.getContentType())
        println(y.entity.contentType)
    }
  }
}

This prints:

HttpEntity.Strict(application/json,{"nominative":"komunikacja","genitive":"komunikacji","dative":"komunikacji","accusative":"komunikację","instrumental":"komunikacją","locative":"komunikacji","vocative":"komunikacjo"})
application/json
application/json

Here come the questions:
1. Why ResponseEntity supplies getContentType() and contentType()? They return the same thing. 2. Getting the contentyType is easy, you have two ways for doing it, but how can I get the content itself, so I can play (i.e. parse it using play) with the json!

GA1
  • 1,568
  • 2
  • 19
  • 30
  • You can access the entities data with `y.entity.data`, which returns a `ByteString`. In your case it should be sufficient to just call `utf8String` on the `ByteString`, to get a json string which you can parse. – thwiegan Jun 15 '16 at 16:57
  • 1
    The `getContentType()` getter exist only for Java compatibility. In Scala you should use `contentType` – WelcomeTo Jun 15 '16 at 19:06

1 Answers1

0

You can use entity.data.toString for Binary content type, or the following code piece

data.decodeString(nb.charset.value)

Please follow the HttpEntity.Strict.toString implementation here for detail:

https://github.com/akka/akka/blob/master/akka-http-core/src/main/scala/akka/http/scaladsl/model/HttpEntity.scala#L316

LynxZh
  • 825
  • 5
  • 9