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

查看:83
本文介绍了无法使用"writes"将通用案例类转换为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]]:

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].

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

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