如果我没弄错的话,这个BodyParsers.parse.json
会将request.body
解析为json
def getUser(id: Int) = Action (BodyParsers.parse.json) { implicit request =>
var parsedJson = request.body.validate[MyCustomUserModel]
parsedJson.fold(
errors => {
println("Something wrong...")
},
obj => {
println("This would be my name : " + obj.name)
println("This would be my age : " + obj.age)
}
Ok(Json.obj("status"->"Ok"))
}
但是,如果根本没有发送正文,或者json与所有必需的模型不匹配,则会抛出异常。我想知道是否有可能处理这些错误?
答案 0 :(得分:0)
如果要使用parse.json
解析请求正文,则应保证请求的内容类型为“application / json”,可通过以下代码进行检查:
val contentType = request.contentType
play.api.Logger.info("contentType: " + contentType)// just check the log info
使用request.body.validate[MyCustomUserModel]
时,您要做的另一件事是为您的案例类定义Json Reads
。例如,您的MyCustomerUserModel
定义如下:
case class MyCustomUserModel(name: String, age: Int)
Reads[myCustomUserModel]
的定义如下:
implicit val myCustomUserModelReads: Reads[MyCustomUserModel] = (
(JsPath \ "name").read[String] and
(JsPath \ "age").read[Int]
)(MyCustomUserModel.apply _)
祝你好运