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

前端 未结 4 843
时光取名叫无心
时光取名叫无心 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:38

    I'd prefer this solution with trait, but in case you do want to make your case class generic you could use one of 2 approaches.

    In case you don't have to use Page[_], i.e. you'll always call toJson on Page[Int] or Seq[Page[String]], but not on Page[_] or Seq[Page[_]]:

    object Page {
      implicit def pageWriter[T: Writes](): Writes[Page[T]] = Json.writes[Page[T]]
    }
    

    In case you have to serialize Page[_]:

    case class Page[T](items: Seq[T],
                       pageIndex: Int,
                       pageSize: Int,
                       totalCount: Long)(
          implicit val tWrites: Writes[T])
    
    object 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)
        }
      }
    }
    

提交回复
热议问题