2

I am trying to make a generic Writer to get me the String representation of a json with Play Json. What I've got till now is

import com.twitter.finatra.http.Controller
import play.api.libs.json.{Json, Writes}

trait MyController extends Controller {
  def handle(request: AnyRef) =
    response
     .ok
     .json(createJsonResponse(manage(request)))
     .toFuture

   def manage[T : Writes](request: AnyRef): T

  // There should be an implicit Writes[T] in scope
   def createJsonResponse[T : Writes](data: T) = Json.stringify(Json.toJson[T](data))
}

I have case class TotalsForResponse(issuer: String, total: Int) defined and

  object JsonFormatters {
   implicit val totalsForResponseWrites = Json.format[TotalsForResponse]
  }

This should provide me at compile with an implicit Writes[T] in scope. IN one of my controllers I have

def manage[T : Writes](request: AnyRef) = request match {

case TotalInvestorsForRequest(issuer) =>
  TotalsForResponse(issuer,
    TitleSectionDBHandler.totalInvestorsFor(issuer))
  .asInstanceOf[T]
}

which results in diverging implicit expansion for type play.api.libs.json.Writes[Nothing] at compile time. This was taken from this example which I couldn't get it to work. Any ideas?

Community
  • 1
  • 1
Tomas Duhourq
  • 81
  • 1
  • 6
  • How an implicit resolution error can occur at runtime? – cchantep May 22 '15 at 16:03
  • Corrected that to 'compile' thanks! – Tomas Duhourq May 22 '15 at 16:23
  • I don't see anywhere in the code you posted in which generic type `T` is actualised (I mean a concrete type is given as the generic type `T`). The whole code seems a bit weird to me, not sure what you want to achieve but I would first make sure that `Json.toJson[TotalsForResponse]` compiles successfully. – Nader Ghanbari May 24 '15 at 09:55
  • Hi Nader, `Json.toJson(TotalsForResponse(issuer, total))` does compile successfully in the manage function, but not at MyController scope, although I'm importing the JsonFormatters correctly inside, type T would be any type defining a Writes[T] over there. – Tomas Duhourq May 24 '15 at 19:13
  • @TomasDuhourq did you get it working ? – Daniel Aug 15 '16 at 16:38

1 Answers1

0

In the example you linked, you forgot to add import JsonFormatters._ to bring the Format[T] into scope.

Ryan
  • 7,227
  • 5
  • 29
  • 40