Parse HTTP POST Response JSON Body in scala

1.4k views Asked by At

I'm sending an http post request as such:

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()

}

My response body is in the form:

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

I want to parse this response to get the value of "token" ("xyz") in Scala. How do you do this?

1

There are 1 answers

0
Philluminati On

There's a syntax you can use on Play framework like this:

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

You can read more about it here:

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