【发布时间】:2016-10-16 20:16:34
【问题描述】:
我对返回 json 的 rest 服务进行了 GET HTTP 调用。我想将 json 解析为 scala 对象,但在这里我被卡住了。我正在使用 Akka api,但无法从 Akka 的 ResponseEntity
中检索 content这是我的 sbt 文件:
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"
)
}
这是应用程序
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)
}
}
}
打印出来:
HttpEntity.Strict(application/json,{"nominative":"komunikacja","genitive":"komunikacji","dative":"komunikacji","accusative":"komunikację","instrumental":"komunikacją","locative":"komunikacji","vocative":"komunikacjo"})
application/json
application/json
问题来了:
1. 为什么 ResponseEntity 提供 getContentType() 和 contentType()?他们返回同样的东西。
2.获取contentyType很简单,有两种方法,但是我怎样才能获取内容本身,所以我可以用json播放(即使用play解析它)!
【问题讨论】:
-
您可以使用
y.entity.data访问实体数据,它返回ByteString。在您的情况下,只需在ByteString上调用utf8String即可获得可以解析的 json 字符串。 -
getContentType()getter 仅用于 Java 兼容性。在 Scala 中,您应该使用contentType
标签: scala akka httpentity