Unable to convert generic case class to json using “writes”

前端 未结 4 841
时光取名叫无心
时光取名叫无心 2021-02-03 12:01

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 {

  i         


        
4条回答
  •  臣服心动
    2021-02-03 12:22

    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))
    

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

提交回复
热议问题