【问题标题】:generic case class to json using writter使用 writer 将通用案例类转换为 json
【发布时间】:2014-04-18 12:27:52
【问题描述】:

我正在尝试将此模型转换为 Json,但我总是收到错误“未找到匹配未应用参数的应用函数”。

我尝试实现两个不同的写入器来执行此操作,但都不起作用。

这是我的模型:

case class Page[T](
    var data: List[T],
    var previous: String,
    var next: String,
    var totalPageCount: Int)(implicit val tWrites: Writes[T])

object Page {

    // Both Writters generate an "No apply function found matching unapply parameters" error
    implicit val pageWrites = Json.writes[Page[_]]

    implicit def pageWriter[T]: Writes[Page[T]] = new Writes[Page[T]] {
        def writes(o: Page[T]): JsValue = {
            implicit val tWrites = o.tWrites
            val writes = Json.writes[Page[T]]
            writes.writes(o)
        }
    }
}

有人有解决办法吗?

【问题讨论】:

    标签: json scala serialization


    【解决方案1】:

    如果可能的话,语法可能看起来像这样:

    implicit def pageWrites[T: Writes]: Writes[Page[T]] = Json.writes[Page[T]]
    

    很遗憾,这不适用于 JSON Inception(Json.writes 后面的宏),因此您需要使用标准的速记:

    implicit def pageWrites[T: Writes]: Writes[Page[T]] = (
      (__ \ 'data).write[List[T]] and
      (__ \ 'previous).write[String] and
      (__ \ 'next).write[String] and
      (__ \ 'totalPageCount).write[Int]
    )(unlift(Page.unapply[T]))
    

    附带说明一下,从模型代码中消除对序列化的担忧可能是一个好主意 - 您可以删除隐含的 Writes 参数并使用此处给出的 pageWrites

    【讨论】:

    • 这项工作正常,但我需要添加一个 listWrites 来序列化通用 List[T] 类型。因此我添加了这个:implicit def listWrites[T](implicit fmt: Writes[T]): Writes[List[T]] = new Writes[List[T]] { def writes(ts: List[T]) = JsArray (ts.map(t => Json.toJson(t)(fmt))) } 但现在我在执行我的项目时在此 listWrites 上收到“MatchError:null”消息。
    • 您不需要为List[T] 添加作者——Play 会为您提供。
    • 如果我不添加它,我会在 List[T] 上收到此错误:“No Json deserializer found for type java.util.List[T]. Try to implement an implicit Writes or Format for this类型。”
    • 那是因为 java.util.List 与 Scala 的 List 不同。您可以在案例类中转换为 Scala 列表吗?
    • 好吧,我没有看到它不是同一个 List 对象。不确定我是否可以转换为 Scala 版本。无法为 java.util.List[T] 类型编写通用编写器?
    猜你喜欢
    • 2014-02-17
    • 2016-07-27
    • 1970-01-01
    • 2023-01-27
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    相关资源
    最近更新 更多