在应用到类之前将转换应用到play框架json元素 [英] Applying conversion to play framework json element before applying to class

查看:74
本文介绍了在应用到类之前将转换应用到play框架json元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个班级

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
}

问题是日期格式不能直接转换为日期,我想以某种方式获取该字符串,并使用

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

然后将其传递给Token构造函数,但我似乎无法弄清楚如何在apply函数中做到这一点

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

推荐答案

如果您具有特殊的日期格式,则可以将String映射到Date

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

这篇关于在应用到类之前将转换应用到play框架json元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆