summerNight
summerNight

Reputation: 1496

Read a JSON value from request.body in Scala & Play Framework

I am sending a JSON data from my angular form into a Play Framework Controller. The Controller receives the messages and when I console print it, it looks like the following:

{"username":"{   \"tID\": 123,   \"cID\": \"TEST\",   \"version\": 1}"}

What I am doing so far is: [Note: I am using play.api.libs.json]

def sendMessage = Action(parse.json) {
  request =>
  val message: JsValue = request.body
  val cID = (message \ "cID").get
}

However I am getting an error java.util.NoSuchElementException: None.get because its not able to retrieve the cID from the JSON string? How do I get the value for cID without the escape character \

Upvotes: 0

Views: 1654

Answers (1)

blueiur
blueiur

Reputation: 1507

value of "username" is encoded Json String, because you should decode Json String

Try this.

def sendMessage = Action(parse.json) { request =>
  val message: JsValue = request.body
  val userNameJsonStr = (message \ "username").as[String]
  val value = Json.parse(userNameJsonStr)
  val cID = (value \ "cID")
}

Upvotes: 1

Related Questions