【问题标题】:Custom write for DataTime in JSON Serializer在 JSON 序列化器中为 DateTime 自定义写入
【发布时间】:2015-05-23 13:45:19
【问题描述】:

如何在 JSON 序列化程序中为 DateTime 获得自定义行为? 我的目标是只连载年份。

这是我的模型:

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

【问题讨论】:

    标签: json scala playframework playframework-2.3


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

    【讨论】:

      猜你喜欢
      • 2011-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-08
      • 2011-04-12
      • 1970-01-01
      相关资源
      最近更新 更多