secret
Last active

  • Download Gist
RichJsPath.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
package controllers
 
import play.api._
import play.api.mvc._
import play.api.libs.json._
import play.api.libs.functional.syntax._
 
object RichJs {
implicit class RichJsPath(js: JsPath) extends JsPath {
// Read T element or try to convert from String
def readStringified[T](toT: String => T)(implicit r: Reads[T], rS: Reads[String]): Reads[T] =
Reads.at[T](js)(r) orElse Reads.at[String](js)(rS).map(toT(_)) // There is certainly a way to use automatic conversion...
// Read Int and fallback to String conversion
def readStringifiedInt: Reads[Int] = readStringified[Int](_.toInt)
}
}
 
case class Example(name: String, number: Int)
 
object Example {
import RichJs._
implicit val formater = (
(__ \ 'name).format[String] and
(__ \ 'number).format((__).readStringifiedInt)
)(Example.apply _, unlift(Example.unapply _))
}
object Application 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(Json.toJson(json2))
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.