使用播放json问题序列化LocalDateTime

时间:2018-02-12 14:29:17

标签: json scala playframework playframework-2.0

我有个人案例类:

case class Person(name: String, createdAt: LocalDateTime)

能够将人物对象序列化为json,以便我可以将其返回给用户 我有一个血清剂:

object PersonSerializer {
  implicit val PersonFormat: OFormat[Person] = Json.format[Person]
}

然后我在控制器中导入这个序列化程序,所以当我可以将结果返回到json这样使用时:

def getPeople: Action[AnyContent] = Action.async {
    peopleDao.getAllPeople.map(people => Ok(Json.toJson(res)))
}

但是,我收到了这个错误:

  

错误:(39,55)没有play.api.libs.json.Format的实例可用   对于隐式作用域中的org.joda.time.LocalDateTime(提示:if   在同一个文件中声明,确保它之前已声明为隐式   val AFormat:OFormat [Account] = Json.format [Account]

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

你的回答几乎就在堆栈跟踪中。基本上,为了格式化Person,Play的序列化程序需要知道如何序列化LocalDateTime。你应该尝试类似的东西:

object PersonSerializer {
    implicit val LocalDateFormat: OFormat[LocalDateFormat] = 
        new OFormat[LocalDateFormat](){ /*...*/ }
    implicit val PersonFormat: OFormat[Person] = Json.format[Person]
}

我建议您查看此post,此onedocumentation

答案 1 :(得分:0)

另一种选择是使用jsoniter-scala:https://github.com/plokhotnyuk/jsoniter-scala

您将获得java.time.*类的支持,其吞吐量和吞吐量超过10倍。序列化。

只需看看Jason-scala与Circe,Jackson和Play-JSON的ArrayOfLocalDateFormatBenchmark的结果:http://jmh.morethan.io/?source=https://plokhotnyuk.github.io/jsoniter-scala/oraclejdk8.json