Creating a universal Json serialization function

Is it possible to create a generic function in Scala using Play Framework 2.2 that will serialize an arbitrary object in JSON without the need for a writer or formatting?

For example, this non-generic code will generate the JSON response given by the client:

import play.api.libs.json._
import play.api.libs.functional.syntax._

case class Customer(id: Int, name: String)

object scratch {
  val p = Customer(1, "n")                        
  //> p  : Customer = Customer(1,n)

  def createJsonResponseCustomer(data: Customer) = {
    implicit val formatter = Json.format[Customer]
    Json.obj("success" -> true, "data" -> Json.toJson[Customer](data))
  }

  createJsonResponseCustomer(p)                   
  //> res0: play.api.libs.json.JsObject = {"success":true,"data":{"id":1,"name":"n"}}
}

To avoid having to define a formatter for every other object, I would like to create a generic function like this:

def createJsonResponse[T](data: T) = {
  implicit val formatter = Json.format[T]
  Json.obj("success" -> true, "data" -> Json.toJson[T](data))
}

But this attempt creates an error No unapply function foundin Json.format[T].

In other words, this works:

def getFormatter(c: Customer) = Json.format[Customer]

but this is not so:

def getFormatterGeneric[T](c: T) = Json.format[T]

Is there any way around this?

+4
source share
1 answer

-, , . , , . , , , , , .

" " , ,

object JsonFormatters {
  implicit val customerWrites: Format[Customer] = Json.format[Customer]
}

import JsonFormatters._ , JSON.

, , : . Writes[T].

def createJsonResponse[T](data: T)(implicit writes: Writes[T]) =
  Json.obj("success" -> true, "data" -> Json.toJson[T](data))

, , ..

def createJsonResponse[T : Writes](data: T) = ...

, Writes[T]; T, .

, Writes[T] Format[T]; JSON , Format[T], Reads[T].

+9

All Articles