【问题标题】:Json Coast to Coast Play framework : Serializing Joda DateTimeJson Coast to Coast Play 框架:序列化 Joda DateTime
【发布时间】:2014-05-30 00:43:05
【问题描述】:

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

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

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”模型的验证失败感到困惑。 提前感谢,任何帮助将不胜感激。

【问题讨论】:

  • 不是因为路径不匹配吗?您需要在 Reads 对象中包含类似 (__ \ "schedule" \ "startDate").read[String]... 的内容。

标签: scala playframework-2.2 scala-2.10 reactivemongo


【解决方案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)))

【讨论】:

    【解决方案2】:
    猜你喜欢
    • 1970-01-01
    • 2015-04-28
    • 2011-08-07
    • 2015-10-29
    • 2015-01-11
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 2011-03-17
    相关资源
    最近更新 更多