如何在Play Json中使用Joda DateTime [英] How to use Joda DateTime with Play Json

查看:116
本文介绍了如何在Play Json中使用Joda DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发Play应用程序,并且试图在我的case类中使用Joda DateTime对象.

I'm developing a Play application, and I'm trying to use a Joda DateTime object into my case class.

package model

import org.joda.time.DateTime
import play.api.libs.json._

case class User(name: String, created: DateTime)

object User {
  implicit val yourJodaDateReads = Reads.jodaDateReads("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
  implicit val yourJodaDateWrites = Writes.jodaDateWrites("yyyy-MM-dd'T'HH:mm:ss.SSSZ'")
  implicit val userFormat = Json.format[User]

  def main(args: Array[String]) {

  val value = Json.parse("{ \"name\" : \"hello\" , \"created\" : \"2015-07-16T20:32:04.046+02:00\" }")

  println(Json.toJson(new User("user", new DateTime())))
  println(Json.fromJson(value))
 }
}

基于此解决方案,我收到此错误:

Based on this solution, I'm getting this error:

Error:(18, -1) Play 2 Compiler: 
 /activator-1.3.2/notifier-app/app/model/Test.scala:18: ambiguous implicit    values:
 both value yourJodaDateReads in object User of type => play.api.libs.json.Reads[org.joda.time.DateTime]
    and value userFormat in object User of type => play.api.libs.json.OFormat[model.User]

我正在使用Activator 1.3.2和Play 2.3.8.

I'm using Activator 1.3.2 and Play 2.3.8.

能给我建议吗?

谢谢.

更新

我了解 play.api.libs.json.Reads

implicit val DefaultJodaDateReads = jodaDateReads("yyyy-MM-dd") 

如何解决此问题?

推荐答案

期待更好的选择,这里是我的解决方法:

Expecting a better alternative, here my workaround:

val dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

val jodaDateReads = Reads[DateTime](js =>
  js.validate[String].map[DateTime](dtString =>
    DateTime.parse(dtString, DateTimeFormat.forPattern(dateFormat))
  )
)

val jodaDateWrites: Writes[DateTime] = new Writes[DateTime] {
  def writes(d: DateTime): JsValue = JsString(d.toString())
}

val userReads: Reads[User] = (
  (JsPath \ "name").read[String] and
    (JsPath \ "created").read[DateTime](jodaDateReads)
  )(User.apply _)

val userWrites: Writes[User] = (
  (JsPath \ "name").write[String] and
   (JsPath \ "created").write[DateTime](jodaDateWrites)
  )(unlift(User.unapply))

implicit val userFormat: Format[User] = Format(userReads, userWrites)

这篇关于如何在Play Json中使用Joda DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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