【问题标题】:Parsing JSON Date Time in Scala/Play在 Scala/Play 中解析 JSON 日期时间
【发布时间】:2014-10-15 15:35:03
【问题描述】:

我定义了以下读取:

import org.joda.time.DateTime;

implicit val userInfoRead: Reads[UserInfo] = (
  (JsPath \ "userName").readNullable[String] and
] (JsPath \ "startDate").readNullable[DateTime]
 (UserInfo.apply _)

传入以下 JSON 对象:

  "userInfo" : {
    "userName": "joeuser",
    "startDate": "2006-02-28"
  }

当我验证此数据时,我收到以下错误:

(/startDate,List(ValidationError(validate.error.expected.jodadate.format,WrappedArray(yyyy-MM-dd))))))

对我在格式中遗漏的内容有什么建议吗?

【问题讨论】:

  • 第一个代码位的第 5 行有一个免费的],应该在那里吗?
  • 不,这是复制/粘贴错字。
  • 这里是示例代码中的复制/粘贴错误,而不是程序代码中。

标签: json scala datetime playframework-json


【解决方案1】:

据我所知,问题可能只是格式不符合 Joda 的预期。我简化了一点,这对我有用:

scala> import org.joda.time.DateTime
import org.joda.time.DateTime

scala> case class UserInfo(userName: String, startDate: DateTime)
defined class UserInfo

scala> implicit val dateReads = Reads.jodaDateReads("yyyy-MM-dd")
dateReads: play.api.libs.json.Reads[org.joda.time.DateTime] = play.api.libs.json.DefaultReads$$anon$10@22db02cb

scala> implicit val userInfoReads = Json.reads[UserInfo]
userInfoReads: play.api.libs.json.Reads[UserInfo] = play.api.libs.json.Reads$$anon$8@52bcbd5d

scala> val json = Json.parse("""{
     |     "userName": "joeuser",
     |     "startDate": "2006-02-28"
     |   }""")
json: play.api.libs.json.JsValue = {"userName":"joeuser","startDate":"2006-02-28"}

scala> json.validate[UserInfo]
res12: play.api.libs.json.JsResult[UserInfo] = JsSuccess(UserInfo(joeuser,2006-02-28T00:00:00.000-05:00),)

【讨论】:

  • 谢谢。我尝试了您的确切代码,并得到了与我的代码收到的完全相同的错误消息。想知道我正在使用的 Scala 版本是否存在错误??
  • @user2639243 你用的是什么版本?
  • 使用 Scala 2.10.0,部分播放 2.1.4。
  • 我明白了。我认为升级不是一个可行的选择?
  • 正确,无法升级
猜你喜欢
  • 1970-01-01
  • 2017-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-13
  • 1970-01-01
  • 2015-08-30
相关资源
最近更新 更多