本文介绍了使用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写入时转换类型
发布评论