首页 文章

如何玩和Joda:如何通过Scala序列化和反序列化DateTime?

提问于
浏览
1

我正在使用Play 2.3.7,Scala 2.11.4版 .

我有这种课 . 我想将对象序列化和反序列化为json,并从json序列化为对象 .

case class Person(var id: Int = 0,
                  var first_name: String = "",
                  var last_name: String = "",
                  var email: String = "",
                  var date_of_birth: DateTime = new DateTime())

在阅读文档后,我发现我需要自己的隐式读写器 . 所以我尝试如下:

implicit val personWrites: Writes[Person] = (
  (__ \ "id").write[Int] ~
  (__ \ "first_name").write[String] ~
  (__ \ "last_name").write[String] ~
  (__ \ "email").write[String] ~
  (__ \ "date_of_birth").write[DateTime])

(unlift(Person.unapply))

implicit val userReads: Reads[Person] = (
(__ \ "id").read[Int] ~
  (__ \ "first_name").read[String] ~
  (__ \ "last_name").read[String] ~
  (__ \ "nickname").read[String] ~
  (__ \ "date_of_birth").read[DateTime] 
 )(Person.apply _)

我得到编译器错误:重载方法值适用于替代品......

请告诉我怎么做?谢谢!

1 回答

  • 1

    您不需要编写自己的读/写,除非它们不对称或您正在做自定义的事情 . Json有一种格式方法,可以根据案例类创建格式化程序 . 它还有一些默认的格式化程序,包括Joda DateTime类 .

    implicit val personFormatter:Format[Person] = Json.format[Person]
    

相关问题