我对返回JSON的REST服务进行HTTP调用。我想将JSON解析为Scala对象,但是我被卡住了。我正在使用akka api,我无法从akka的 wendersentity
中检索 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.为什么响应性提供getContentType()和contentType()?他们返回同一件事。2.获得ContrentyType很容易,您有两种方法可以做到这一点,但是我如何获得内容本身,因此我可以使用JSON!
您可以将entity.data.tostring用于二进制内容类型,或以下代码pries
data.decodeString(nb.charset.value)
请在此处遵循httpentity.strict.tostring实现的详细信息:
https://github.com/akka/akka/blob/master/akka-http-core/src/main/main/scala/scala/akka/http/scaladsl/scaladsl/model/mmodel/httpentity.scala#l316