在应用到 class 之前应用转换到 play framework json 元素

Applying conversion to play framework json element before applying to class

我有一个class这样

case class Token(
              creationDate: Date,
              expires: Option[Date]
            ) {
  def toJson(): String = Json.stringify(Json.toJson(this))
}

object Token {
  def fromJson(json: String): Token = Json.parse(json).as[Token]

  implicit val tokenReads: Reads[Token] = (
    (JsPath \ "creation_date").read[Date] and
      (JsPath \ "expires").readNullable[Date]
    ) (Token.apply _)

  implicit val tokenWrites: Writes[Token] = (
    (JsPath \ "creation_date").write[Date] and
      (JsPath \ "expires").writeNullable[Date]
    ) (unlift(Token.unapply))

}

从 json 像

创建的
{
  "creation_date": "2014-05-22T08:05:57.556385+00:00",
  "expires": null
}

问题是日期格式无法直接转换为日期,我希望以某种方式获取该字符串,并使用

进行转换
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
String string2 = "2001-07-04T12:08:56.235-07:00";
Date result2 = df2.parse(string2);

然后将其传递给 Token 构造函数,但我似乎无法弄清楚如何在应用函数中执行此操作

如果你有特殊的日期格式,你可以将字符串映射到日期

def strToDate(string2: String): Date = {
  //... something such
  val df2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
  df2.parse(string2);
}

implicit val tokenReads: Reads[Token] = (
  (JsPath \ "creation_date").read[String].map(strToDate) and
     (JsPath \ "expires").readNullable[String].map(_.map(strToDate))
  ) (Token.apply _)