Home > Blockchain >  cannot be applied to (play.api.mvc.AnyContent)
cannot be applied to (play.api.mvc.AnyContent)

Time:02-22

when i try to convert my content of request body to json this happens..

code:

def addItem() = Action { implicit request =>
    val content:AnyContent = request.body
    val res = Json.parse(content)
    Ok("done")   
  }

sbt compile msg:

**overloaded method parse with alternatives:
[error]   (input: Array[Byte])play.api.libs.json.JsValue <and>
[error]   (input: java.io.InputStream)play.api.libs.json.JsValue <and>
[error]   (input: String)play.api.libs.json.JsValue
[error]  cannot be applied to (play.api.mvc.AnyContent)
[error]     val res = Json.parse(content)**

i want to know why i can't convert my content as json ?

CodePudding user response:

AnyContent provides a helper method asJson:

ef addItem() = Action { implicit request =>
    val content: AnyContent = request.body
    val res: Option[JsValue] = content.asJson
    Ok("done")   
}

Or, you can use Play's body parser directly:

def addItem() = Action(parse.json) { implicit request: Request[JsValue] =>
  val content: JsValue = request.body
  // ...
  Ok("done")   
}

It will give a HTTP 400 automatically if content is not JSON.

See https://www.playframework.com/documentation/2.8.x/ScalaBodyParsers

  • Related