以下代码获取请求正文并验证并创建 json: object ValidateDBConfigJson {
implicit val reads: Reads[ValidateDetails] = (
(JsPath "name").read[String].filter(JsonValidationError("Invalid name"))(_.length > 0) and
(JsPath "email").read[String].filter(JsonValidationError("Invalid email"))(_.length > 0) and
)(ValidateDetails.apply _)
}
def index() = Action { implicit request =>
val bodyAsJson = request.body.asJson.get
bodyAsJson.validate[ValidateDetails] match {
case success: JsSuccess[ValidateDetails] => {
Ok(Json.parse("succeeded!"))
}
case JsError(error) =>
BadRequest(JsError.toJson(error))
}
}
json 如下所示:
{
"obj.name": [
{
"msg": [
"error.expected.jsstring"
],
"args": []
}
],
"obj.email": [
{
"msg": [
"Invalid email"
],
"args": []
}
]
}
我希望以以下格式进行结构化:
{
"ErrorMessages" :
[
"error.expected.jsstring",
"Invalid email"
]
}
序言:当我使用 Play 解析 JSON 时,我更喜欢使用案例类/对象而不是隐式读取,因此此答案将涵盖执行此操作的方法。可能有一种更简单的方法可以对隐式读取执行此操作,但我对隐式读取并不熟悉。
首先,为将从 JSON 获取的所有内容定义一个case class
:
object Input {
case class Err(msg: Seq[String], args: Seq[String])
object Err {
implicit val format: OFormat[Err] = Json.format[Err]
}
case class ValidateDetails(`obj.name`: Seq[Err], `obj.email`: Seq[Err])
object ValidateDetails {
implicit val format: OFormat[ValidateDetails] = Json.format[ValidateDetails]
}
}
注意:Play 不知道如何处理用户定义的案例类,所以我也为Err
制作了一个案例类。implicit val format: OFormat[ValidateDetails] = Json.format[ValidateDetails]
行和implicit val format: OFormat[Err] = Json.format[Err]
行很神奇,可以为您完成所有读取/写入。
接下来,为输出 JSON 定义一个案例类,并定义一个函数,该函数将输入案例类转换为输出案例类:
object Output {
case class OutputJson(`ErrorMessages`: Seq[String])
object OutputJson {
implicit val format: OFormat[OutputJson] = Json.format[OutputJson]
}
// take msg Seq from name & email and add together into single Seq
def inputToOutput(input: Input.ValidateDetails): OutputJson = {
OutputJson(input.`obj.name`.flatMap(_.msg) ++ input.`obj.email`.flatMap(_.msg))
}
}
最后,将其放入映射到routes
文件中的 POST 路由的方法中:
def index() = Action { implicit request =>
val bodyAsJson = request.body.asJson.get
bodyAsJson.validate[Input.ValidateDetails] match {
case success: JsSuccess[Input.ValidateDetails] =>
// turn the JSON into the Output case class and parse that as JSON
val output: JsValue = Json.toJson(Output.inputToOutput(success.value))
Ok(output)
case JsError(error) =>
BadRequest(JsError.toJson(error))
}
}
现在,如果您在端口 9000 上运行 Play 应用并使用以下 JSON 正文 POST http://localhost:9000/...
{
"obj.name": [
{
"msg": [
"error.expected.jsstring"
],
"args": []
}
],
"obj.email": [
{
"msg": [
"Invalid email"
],
"args": []
}
]
}
。输出将是:
{
"ErrorMessages": [
"error.expected.jsstring",
"Invalid email"
]
}
我希望这能回答你的问题。