我正在开发Play应用程序,并且试图在我的case类中使用Joda DateTime对象。
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)) } }
基于此解决方案,出现此错误:
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。
你能给我建议吗?
提前致谢。
更新
我了解 play.api.libs.json.Reads中 的隐式值存在冲突 __
implicit val DefaultJodaDateReads = jodaDateReads("yyyy-MM-dd")
我该如何解决这个问题?
期待更好的选择,这是我的解决方法:
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)