如何在DateTime的JSON Serializer中获取自定义行为? 我的目标是只统一年份。
这是我的模特:
case class Model(id: Option[Int], name: String, userID: String, date: DateTime, material: String, location: String, text: String, pathObject: Option[String], pathTexure: Option[String], pathThumbnail: Option[String])
object Model {
implicit val tswrites: Writes[DateTime] = Writes { (dt: DateTime) => JsString(dt.year.get.toString) }
implicit val modelWrites: Writes[Model] = (
(JsPath \ "id").write[Option[Int]] and
(JsPath \ "name").write[String] and
(JsPath \ "userId").write[String] and
(JsPath \ "date").write[DateTime] and
(JsPath \ "material").write[String] and
(JsPath \ "location").write[String] and
(JsPath \ "text").write[String] and
(JsPath \ "f1").write[Option[String]] and
(JsPath \ "f2").write[Option[String]] and
(JsPath \ "f3").write[Option[String]])(unlift(models.Model.unapply))
}
日期字段序列化为631148400000
所需的日期字段序列化为1990
答案 0 :(得分:1)
我已经解决了,
以下是解决方案:
object Model {
implicit val tswrites: Writes[DateTime] = Writes { (dt: DateTime) => JsString(dt.year.get.toString) }
implicit val modelWrites: Writes[Model] = (
(JsPath \ "id").write[Option[Int]] and
(JsPath \ "name").write[String] and
(JsPath \ "userId").write[String] and
Writes.at[DateTime]((JsPath \ "date"))(tswrites) and
(JsPath \ "material").write[String] and
(JsPath \ "location").write[String] and
(JsPath \ "text").write[String] and
(JsPath \ "f1").write[Option[String]] and
(JsPath \ "f2").write[Option[String]] and
(JsPath \ "f3").write[Option[String]])(unlift(models.Model.unapply))
}