Json Coast to Coast Play框架:序列化Joda DateTime

时间:2014-05-30 00:43:06

标签: scala playframework-2.2 scala-2.10 reactivemongo

大家好我是新玩的框架,如果有人知道下面提到的更好的方法,请告诉我。

所以我有一个模型和它的读/写/格式

case class Schedule (startDate: DateTime, endDate: DateTime)


object ScheduleSerializers {


  val userDateFormatter = "dd/MM/yyyy HH:mm:ss"
  val nonImplicitUserFormatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss")
  implicit val jodaDateTimeReads = Reads.jodaDateReads(userDateFormatter)
  implicit val jodaDateTimeWrites = Writes.jodaDateWrites(userDateFormatter)

  implicit val readSchedule: Reads[Schedule] = (
    (__ \ "startDate").read[String].map[DateTime](dt => DateTime.parse(dt, nonImplicitUserFormatter)) and
      (__ \ "endDate").read[String].map[DateTime](dt => DateTime.parse(dt, nonImplicitUserFormatter))
    )(Schedule)

  implicit val writeSchedule: Writes[Schedule] = (
    (__ \ "startDate").write[String].contramap[DateTime](dt => nonImplicitUserFormatter.print(dt)) and
      (__ \ "endDate").write[String].contramap[DateTime](dt => nonImplicitUserFormatter.print(dt))
    )(unlift(Schedule.unapply))

  implicit val formatSchdule = Format(readSchedule, writeSchedule)

}

现在我打开播放控制台并执行此操作

val sch = Json.parse(""" {
     | 
     |   "schedule" : { "starDate" : "04/02/2011 20:27:05" , "endDate" : "04/02/2011 20:27:05" }
     | }
     | """)
sch: play.api.libs.json.JsValue = {"schedule":{"starDate":"04/02/2011 20:27:05","endDate":"04/02/2011 20:27:05"}}

sch.validate[Schedule]
res0: play.api.libs.json.JsResult[models.experiment.Schedule] = JsError(List((/endDate,List(ValidationError(error.path.missing,WrappedArray()))), (/startDate,List(ValidationError(error.path.missing,WrappedArray())))))

我收到错误,但如果我尝试解析ex:

的单个日期
scala> val singleDate = Json.parse(""" "04/02/2011 20:27:05" """)
singleDate: play.api.libs.json.JsValue = "04/02/2011 20:27:05"

singleDate.validate[DateTime]
res1: play.api.libs.json.JsResult[org.joda.time.DateTime] = JsSuccess(2011-02-04T20:27:05.000-08:00,)

我很困惑为什么' singleDate'但是可以在' Schedule'上进行验证。模型失败。 在此先感谢,任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

错误很明显:“路径缺失”。

而不是:

 (__ \ "startDate") ...
 (__ \ "endDate") ...

你必须提供真正的道路:

 (__ \ "schedule" \ "startDate") ...
 (__ \ "schedule" \ "endDate") ...

顺便说一下,当您将jodaDateTimeReads定义为implicit时,您无需手动执行此操作。当您的读写操作相同时,请使用Format

这应该足够了:

implicit val formatSchedule: Format[Schedule] = (
  (__ \ "startDate").read[DateTime] and
  (__ \ "endDate").read[DateTime]
)(Schedule.apply, unlift(Schedule.unapply)))

答案 1 :(得分:1)