Christophe
Christophe

Reputation: 107

generic case class to json using writter

I am trying to convert this model to Json but I always got the error "No apply function found matching unapply parameters".

I tried to implement two different writters for doing this but both do not work.

Here is my model:

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

Does anyone has a solution ?

Upvotes: 1

Views: 804

Answers (1)

Travis Brown
Travis Brown

Reputation: 139058

If this were possible, the syntax would probably look something like this:

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

Unfortunately this doesn't work with JSON Inception (the macro that's behind Json.writes), so you'll need to use the standard longhand:

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

As a side note, it's probably a good idea to remove concerns about serialization from your model code—you can just drop the implicit Writes argument and use the pageWrites given here.

Upvotes: 4

Related Questions