I have put all my Json converters in one file JsonUtil, and then have a convertToJson method which tries to convert any object passed to json.
Basically a structure
This works.
def convertToJson[A](a: A)(implicit ev: Format[A] = null): JsValue = {
if (ev != null) {
Json.toJson(a)(ev)
} else {
println("oops")
JsNull
}
}
A bit better version below (perhaps ;)
case class Perhaps[E](value: Option[E]) {
def fold[F](ifAbsent: => F)(ifPresent: E => F): F =
value.fold(ifAbsent)(ifPresent)
}
implicit def perhaps[E](implicit ev: E = null) = Perhaps(Option(ev))
def convertToJson[A](a: A)(implicit p: Perhaps[Format[A]]): JsValue = {
p.fold[JsValue] {
println("oops")
JsNull
} { implicit ev =>
Json.toJson(a)
}
}