使用play json写入时转换类型

时间:2016-02-27 15:22:02

标签: json scala playframework playframework-2.0

继续这个问题Applying conversion to play framework json element before applying to class

我有一个Date对象,我希望以特定格式将其写入json中的字符串。

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

我想成为json' ed:

"creation_date": "2014-05-22T08:05:57.556385+00:00"

将字符串转换为我使用过的日期:

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

然后映射到读取中,但这似乎不可能通过写入

1 个答案:

答案 0 :(得分:0)

遵循write

的定义
def write[T](implicit w: Writes[T])

您可以创建自己的Writes[T]并使用它。

例如

object dateWrite extends Writes[Date] {
  override def writes(o: Date): JsValue = JsString("some formatted date")
}

会将o:Date写入JsString("some formatted date")(您可以使用自己的格式:Date => JsValue),然后在Writes[T]中使用自己的write

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

结果

tokenWrites.writes(Token(new Date(), Some(new Date())))

将是

res1: play.api.libs.json.JsValue = {"creation_date":"some formatted date","expires":"some formatted date"}