使用play json写入时转换类型

编程入门 行业动态 更新时间:2024-10-22 14:41:38
本文介绍了使用play json写入时转换类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

此问题之后应用转换在应用于类之前先播放框架json元素

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

I have a Date object which I want to be written to a string in json in a specific format.

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"

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

To convert the string to a Date I have used:

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

然后将其映射到读取中,但这似乎无法通过写操作实现

And then mapped in the reads, but this doesn't seem to be possible with a write

推荐答案

按照write

def write[T](implicit w: Writes[T])

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

you can create own Writes[T] and use it.

例如

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

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

will write o:Date to JsString("some formatted date") (you can use own format: Date => JsValue), and then use own Writes[T] in 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"}

更多推荐

使用play json写入时转换类型

本文发布于:2023-11-26 17:14:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634480.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:入时   类型   play   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!