-
-
Save julien-lafont/02dca6d1b77f0be6bf72 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 = readStringified[Int](_.toInt) | |
} | |
} | |
case class Example(name: String, number: Int) | |
object Example { | |
import RichJs._ | |
implicit val reader = ( | |
(__ \ 'name).read[String] and | |
(__ \ 'number).readStringifiedInt | |
)(Example.apply _) | |
implicit val writer = Json.writes[Example] // write has no specificity, so you can use Json Macro | |
} | |
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(json1.number + " / " + json2.number) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Or this way https://gist.github.com/02dca6d1b77f0be6bf72/06bad5eeb1aa5218095f3a996f20b0413f42b5e9