6

我定义了以下读取:

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))))))

关于我在格式中遗漏的任何建议?

4

1 回答 1

3

据我所知,问题可能只是格式不符合 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),)
于 2014-10-15T17:56:08.553 回答