1

Given the following case class:

import java.time.LocalDate
case class ReportDateVO(reportDate: LocalDate)

I'm trying to define the implicit json format:

implicit val reportDatesWrite : Writes[ReportDateVO] = (
      (JsPath \ "dt").write[LocalDate]
  ) (unlift(ReportDateVO.unapply))

But I get the following error:

overloaded method value write with alternatives: (t: java.time.LocalDate)(implicit w: play.api.libs.json.Writes[java.time.LocalDate])play.api.libs.json.OWrites[play.api.libs.json.JsValue] (implicit w: play.api.libs.json.Writes[java.time.LocalDate])play.api.libs.json.OWrites[java.time.LocalDate] cannot be applied to (fdic.ReportDateVO ⇒ java.time.LocalDate)

What are these alternatives? there's no default format? how to fix this? I'm using Play 2.5.2.

4

2 回答 2

1

简短的回答是您只能将 JSON 组合器用于具有最少参数数量 2(最多 22 个)的案例类。查看JSON Reads/Writes/Format Combinators的文档, Complex Reads部分。组合器对于读取和写入的工作方式类似,因此复杂读取部分中的简短说明可能会有所帮助。所以基本上编译器对你说的是你不能将fdic.ReportDateVO ⇒ java.time.LocalDate类型的函数传递给方法什么有点奇怪,因为从逻辑上讲,如果你在(JsPath \ "dt")周围有括号.write[LocalDate],应该返回OWrites[LocalDate]的实例,编译器应该报错在OWrites[LocalDate]类型的对象中应用方法。

我认为最好的选择(如果你想有自定义的文件名)是手动实现Writes[LocalDate] 。

implicit val reportDatesWrite: Writes[ReportDateVO] = OWrites[ReportDateVO] {
  rdvo: ReportDateVO => Json.obj(
    "dt" -> DefaultLocalDateWrites.writes(rdvo.reportDate)
  )
}

如果字段名称可以匹配案例类(reportDate)中的参数名称,那么您也可以使用使用 Scala 宏实现的 Play 辅助方法。

implicit val reportDatesWrite: Writes[ReportDateVO] = Json.writes[ReportDateVO]
于 2016-05-07T06:20:08.570 回答
1

PlayJson 仅为 Int、String、Double 等基本类型提供序列化程序 - LocalDate 不是其中之一。

您有正确的想法,但需要更具体并首先为 LocalDate 定义 Combinator:

   implicit val LocalDateWrites: Writes[LocalDate] = Writes {
        (l: LocalDate) => JsString(l.toString())
   }

    implicit val reportDatesWrite : Writes[ReportDateVO] = (
        (JsPath \ "dt").write[LocalDate]
    ) (unlift(ReportDateVO.unapply))
于 2016-05-06T23:11:48.350 回答