Applying conversion to play framework json element

2019-09-10 05:26发布

问题:

I have a class as so

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))

}

Which gets created from json like

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

Problem is that date format cant be converted to a date directly, I am looking to somehow take that string, and convert it using

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);

and then pass it into the Token constructor, but I cant seem to figure out how to do that in the apply function

回答1:

You can map String to Date if you have special date format

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 _)