gpt4 book ai didi

json - 如何在 Play Json 中使用 Joda DateTime

转载 作者:行者123 更新时间:2023-12-04 00:00:22 26 4
gpt4 key购买 nike

我正在开发一个 Play 应用程序,我试图在我的案例类中使用一个 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))
}
}

基于此 solution ,我收到此错误:
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)

关于json - 如何在 Play Json 中使用 Joda DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31462673/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com