无法使用“写入"将通用案例类转换为 json [英] Unable to convert generic case class to json using "writes"

查看:23
本文介绍了无法使用“写入"将通用案例类转换为 json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,我希望能够将其转换为 json:

I have a class which I want to be able to convert to json:

case class Page[T](items: Seq[T], pageIndex: Int, pageSize: Int, totalCount: Long)

object Page {

  implicit val jsonWriter: Writes[Page[_]] = Json.writes[Page[_]]
}

错误是No apply function found matching unapply parameters

推荐答案

您可以为通用案例类 Page[T] 定义 Format[Page[T]] like这个:

You can define Format[Page[T]] for generic case class Page[T] like this:

import play.api.libs.json._
import play.api.libs.functional.syntax._

implicit def pageFormat[T: Format]: Format[Page[T]] =
  ((__  "items").format[Seq[T]] ~
    (__  "pageIndex").format[Int] ~
    (__  "pageSize").format[Int] ~
    (__  "totalCount").format[Long])(Page.apply, unlift(Page.unapply))

尽管此解决方案需要更多的输入,但它使您的案例类 Page[T] 远离隐式参数列表或需要定义 Page[T] 的具体子类.

Although this solution requires more typing, it keeps your case class Page[T] clear of implicit parameter list or need to define concrete subclasses of Page[T].

这篇关于无法使用“写入"将通用案例类转换为 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆