【问题标题】:Play Json Validation is failing on Date field with Error: [error.expected.date.isoformat]播放 Json 验证在日期字段上失败并出现错误:[error.expected.date.isoformat]
【发布时间】:2019-12-12 10:10:14
【问题描述】:

我有一个JsonValidationError

这是我的模型:

case class Account(id: Long, name: String, birthDate: LocalDate)
object Account {
  implicit val accountFormat = Json.format[Account]
}

这是我的控制器操作的一部分:

def updateProfile = Action.async(parse.json) { implicit request =>
  val res = request.body.validate[Account]
  logger.info(request.body.toString)
  logger.info(res.toString)

  ...
}

我有这个输出:

[info] c.a.AccountController - {"id":1,"name":"John","birthDate":"1983-02-11T23:00:00.000Z"}
[info] c.a.AccountController - JsError(List((/birthDate,List(JsonValidationError(List(error.expected.date.isoformat),ArraySeq(ParseCaseSensitive(false)(Value(Year,4,10,EXCEEDS_PAD)'-'Value(MonthOfYear,2)'-'Value(DayOfMonth,2))[Offset(+HH:MM:ss,'Z')])))))

来自客户端的数据似乎是有效的,我不明白那个错误,我认为birthDateisoFormat 中,那么这里可能是什么问题?

请帮忙。

【问题讨论】:

    标签: scala playframework play-json


    【解决方案1】:

    输入的格式与java.time.LocalDate 的预期格式不同。

    尝试使用以下自定义编解码器来解决问题:

    case class Account(id: Long, name: String, birthDate: LocalDate)
    object Account {
      implicit val accountFormat: OFormat[Account] = {
        implicit val customLocalDateFormat: Format[LocalDate] = Format(
          Reads(js => JsSuccess(Instant.parse(js.as[String]).atZone(ZoneOffset.UTC).toLocalDate)),
          Writes(d => JsString(d.atTime(LocalTime.of(23, 0)).atZone(ZoneOffset.UTC).toInstant.toString)))
        Json.format[Account]
      }
    }
    
    val json = """{"id":1,"name":"John","birthDate":"1983-02-11T23:00:00.000Z"}"""
    val account = Json.parse(json).as[Account]
    println(account)
    println(Json.toJson(account))
    

    这段代码 sn-p 的预期输出是:

    Account(1,John,1983-02-11)
    {"id":1,"name":"John","birthDate":"1983-02-11T23:00:00Z"}
    

    【讨论】:

    • 这种自定义的Format不需要实现解析,可以直接使用Reads.localDateReads
    • Reads.localDateReads 不那么严格,允许 JSON 数字作为输入
    • 这不是问题的一部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-19
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    相关资源
    最近更新 更多