在scala中解析HTTP POST响应JSON主体

时间:2020-05-05 13:28:48

标签: json scala post scalaj-http

我正在这样发送http帖子请求:

def Token(url: String, Id: String, key: String): String = {
  val body =
    s"""
      | "id": ${Id}
      | "key": ${key}
      |""".stripMargin

  val request = Http(url).postData(body)
    .header("content-type", "application/json")
    .option(HttpOptions.method("POST"))

  val response = request.execute()

}

我的回复正文的格式为:

{
    "token": "xyz",
    "abc": "defgh"
}

我想解析此响应以获取Scala中“ token”(“ xyz”)的值。你如何做到的?

1 个答案:

答案 0 :(得分:0)

您可以在Play框架上使用如下语法:

response =>
  val json = response.json
  println (json \ "error").asOpt[String]

您可以在此处了解更多信息:

https://www.playframework.com/documentation/2.8.x/ScalaJsonHttp

相关问题