【问题标题】:Serialize LocalDateTime with play json issue使用播放 json 问题序列化 LocalDateTime
【发布时间】:2018-07-22 18:10:12
【问题描述】:

我有一个 Person 案例类:

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(提示:如果 在同一个文件中声明,确保之前声明过)隐式 val AFormat: OFormat[Account] = Json.format[Account]

我该如何解决这个问题?

【问题讨论】:

    标签: json scala playframework playframework-2.0


    【解决方案1】:

    您的答案几乎在堆栈跟踪中。基本上,为了格式化Person,Play 的序列化器需要知道如何序列化LocalDateTime。您应该尝试以下方法:

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

    我建议你看看这个post、这个onedocumentation

    【讨论】:

      【解决方案2】:

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

      您将获得支持 java.time.* 类的构建,解析和序列化的吞吐量提高了 10 倍以上。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-12
        • 1970-01-01
        • 1970-01-01
        • 2019-08-02
        • 2016-07-26
        • 1970-01-01
        • 2016-09-07
        相关资源
        最近更新 更多