Created
April 5, 2017 08:22
-
-
Save xring/fd025b3e1bf22bf253503fb501bc819b 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
case class Person1(name: String, age: Int, other: Option[String]) | |
case class Person2(name: String, age: Int, other: String) | |
import play.api.libs.functional.syntax._ | |
import play.api.libs.json._ | |
implicit val person1Format = ( | |
(JsPath \ "name").format[String] and | |
(JsPath \ "age").format[Int] and | |
(JsPath \ "other").formatNullable[String].inmap[Option[String]](x => Some(x.getOrElse("default")), y => y) | |
) (Person1.apply, unlift(Person1.unapply)) | |
val str1 = | |
""" | |
|{"name":"x", "age":18} | |
""".stripMargin | |
val str2 = | |
""" | |
|{"name":"x", "age":18, "other":"test"} | |
""".stripMargin | |
println(Json.parse(str1).as[Person1]) | |
println(Json.parse(str2).as[Person1]) | |
implicit val person2Format = ( | |
(JsPath \ "name").format[String] and | |
(JsPath \ "age").format[Int] and | |
(JsPath \ "other").formatNullable[String].inmap[String](_.getOrElse("default"), Some(_)) | |
) (Person2.apply, unlift(Person2.unapply)) | |
println(Json.parse(str1).as[Person2]) | |
println(Json.parse(str2).as[Person2]) | |
// Output: | |
// Person1(x,18,Some(default)) | |
// Person1(x,18,Some(test)) | |
// Person2(x,18,default) | |
// Person2(x,18,test) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment