You can easily handle this case with the Json combinators, thanks to the orElse
helper. I rewrote your json formater with the new syntax introduced by Play2.1
import play.api.libs.json._
import play.api.libs.functional.syntax._
object Example {
// Custom reader to handle the "String number" usecase
implicit val reader = (
(__ \ 'name).read[String] and
((__ \ 'number).read[Int] orElse (__ \ 'number).read[String].map(_.toInt))
)(Example.apply _)
// write has no specificity, so you can use Json Macro
implicit val writer = Json.writes[Example]
}
object Test extends Controller {
def index = Action {
val json1 = Json.obj("name" -> "Julien", "number" -> 1000).as[Example]
val json2 = Json.obj("name" -> "Julien", "number" -> "1000").as[Example]
Ok(json1.number + " = " + json2.number) // 1000 = 1000
}
}