我正在使用 Play Framework 和 Scala 创建一个后端 API。我想将传入的请求映射到 scala 对象。对象的实例变量之一是通道列表。这是我目前拥有的:
接受请求并尝试将其映射到用户的控制器方法:
def addUser = Action(parse.json) { request =>
request.body.validate[User].fold({ errors =>
BadRequest(Json.obj(
"status" -> "Error",
"message" -> "Bad JSON",
"details" -> JsError.toFlatJson(errors)
))
}, { user =>
User.create(user.pushToken, user.channels)
Ok(Json.obj("status" -> "OK", "message" -> "User created"))
})
}
用户案例类:
case class User(id: Pk[Long], pushToken: String, channels: List[String])
用户格式化程序:
implicit val userFormat = (
(__ \ "id").formatNullable[Long] and
(__ \ "pushToken").format[String] and
(__ \ "channels").format[List[String]]
)((id, pushToken, channels) => User(id.map(Id(_)).getOrElse(NotAssigned), pushToken, channels),
(u: User) => (u.id.toOption, u.pushToken, u.channels))
用户异常创建方法:
def create(pushToken: String, channels: List[String]) {
DB.withConnection { implicit c =>
SQL("insert into user (pushToken, channels) values ({pushToken}, {channels})").on(
'pushToken -> pushToken,
'channels -> channels
).executeUpdate()
}
}
当我尝试编译时,我得到:
Compilation error[could not find implicit value for parameter extractor: anorm.Column[List[String]]]
理想情况下,我希望能够以用户身份接受这一点:
{
"pushToken":"4jkf-fdsja93-fjdska34",
"channels": [
"channelA", "channelB", "channelC"
]
}
并从中创建一个用户。