I'm using Playframework 2.5 and trying to make a method that all Json request/response controller method calls to avoid writing implicit val foo = Json.writes[Bar] or reads[Bar] inside of each controller method as well as handling basic validation and return the error code.
BaseController which will be inherited by each controller
class BaseController @Inject()(implicit exec: ExecutionContext) extends Controller {
def handleJson[T <: RequestModel,U <: ResponseModel](request: Request[JsValue])(cb: (T) => Future[U]):Future[Result] = {
implicit val convertReq = Json.reads[T]
implicit val convertRes = Json.writes[U]
val reqOpt = request.body.asOpt[T]
reqOpt match {
case Some(data) =>
cb(data).map{x => Ok(Json.toJson(x))}
case None =>
Future.successful(Ok(Json.obj("foo" -> "bar")))
}
}
}
controller
def send = Action.async(parse.json) { req =>
handleJson[RequestCaseClass,ResponseCaseClass](req)( (x) =>
injectedClass.foo(x.bar).map{ case (success: Boolean,mes: String) =>
if(success) SendRes(SomethingForSuccess)
else SendRes(SomethingForError)
}
)
}
Codes above can't be compiled because handleJson's implicit val convertReq = Json.reads[T] and implicit val convertRes = Json.writes[U] says
No Json deserializer found for type T. Try to implement an implicit Reads or Format for this type.
I've already tried making case class's companion object and put the implicit in it though this does not solve anything.
My question is, How can I use implicit value of parameterized types?
Thanks in advance.