将 JSON 隐式验证为列表或类型

Validate JSON Implicit as List or Type

我正在尝试将 json 字符串转换为模型 Temperature。我将其用作 POST 请求。如果我按原样 运行 下面的内容,它将走 JsError 路线并抱怨它期待 List 的验证错误。如果我将验证参数更改为 List[Temperature] 而不是 Temperature 那么它会抱怨 List.

没有隐式定义

我传递的json字符串是:{"typeOfTemperature":"F", "tempVal":90.00}

保存温度方法:

def saveTemperature = Action { request =>
    request.body.asJson match {
      case Some(json) =>
        json.validate[Temperature] match {
          case s: JsSuccess[Temperature] => {
            val temperature: Temperature = s.get
            println(temperature)
            convert.qTemperature.enqueue(temperature)
            Ok
          }
          case e: JsError => {
            //val err: JsError = e.get
            println(e)
            Ok
          }
          case _ => Ok
        }
      case _ => BadRequest
    }
  }

Reads/Writes 隐含:

  implicit val temperatureWrites: Writes[Temperature] = (
    (JsPath \ "typeOfTemp").write[String] and
      (JsPath \ "tempVal").write[Double]
    )(unlift(Temperature.unapply))

  implicit val tempReads: Reads[Temperature] = (
    (JsPath \ "typeOfTemp").read[String](minLength[String](2)) and
      (JsPath \ "tempVal").read[Double](min(-1000.0) keepAnd max(1000.0))
    )(Temperature.apply _)

JSON 键名应与隐式读取键名匹配。 示例:

{"typeOfTemp":"F", "tempVal":90.00}

另外,play提供发件箱支持自动解析请求体为JSON。

示例:

Action(parse.json) { request =>

    request.body.validate[Temperature]
      .fold(
        errors => {
          //log error
          BadRequest(Json.obj("error" -> "invalid request"))
        },
          temperature => {
            println(temperature)
            Ok(Json.toJson(temperature))
          }
      )
  }