运维开发网
广告位招商联系QQ:123077622
 
广告位招商联系QQ:123077622

在Scala / Play中解析JSON日期时间

运维开发网 https://www.qedev.com 2020-07-24 16:51 出处:网络 作者:运维开发网整理
我有以下Read定义: import org.joda.time.DateTime; implicit val userInfoRead: Reads[UserInfo] = ( (JsPath \ "userName").readNullable[String] and ] (JsPath \ "startDate").readNullable[DateTime] (UserInfo.a
我有以下Read定义:

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

关于我在格式化中缺少什么的任何建议?

据我所知,问题可能只是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] = [email protected]

scala> implicit val userInfoReads = Json.reads[UserInfo]
userInfoReads: play.api.libs.json.Reads[UserInfo] = [email protected]

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

扫码领视频副本.gif

0

精彩评论

暂无评论...
验证码 换一张
取 消