Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ryanpbrewster/6792d3f47bff6d0fa8fb087b6d87eeae to your computer and use it in GitHub Desktop.
Save ryanpbrewster/6792d3f47bff6d0fa8fb087b6d87eeae to your computer and use it in GitHub Desktop.
Functional Format[Person] for Working with JSON in Play 2.1 by Greg Methvin
import play.api.libs.functional.syntax._
implicit val personFormat: Format[Person] = (
(__ "id").formatNullable[Id[Person]] and
(
(__ "firstName").format[String] and
(__ "lastName").format[String]
)(Name.apply, unlift(Name.unapply)) and
(__ "email").format(Reads.email) and
(__ "birthDate").format[LocalDate]
)(Person.apply, unlift(Person.unapply))
Json.toJson(Person(
Some(Id(0)),
Name("Arthur","Dent"),
"[email protected]",
new LocalDate("1952-03-11")
))
/* {
"id":0,
"firstName":"Arthur",
"lastName":"Dent",
"email":"[email protected]",
"birthDate":"1952-03-11"
} */
Json.fromJson[Person](Json.parse("""{
"id":0,
"firstName":"Arthur",
"lastName":"Dent",
"email":"[email protected]",
"birthDate":"1952-03-11"
}"""))
/* => JsSuccess(Person(
Some(Id(0)),
Name(Arthur,Dent),
[email protected],
1952-03-11),) */
Json.fromJson[Person](Json.parse("""{
"id":0,
"firstName":"Arthur",
"lastName":"Dent",
"email":"example.com",
"birthDate":"1952-03-11"
}"""))
// => JsError(List((/email,List(ValidationError(validate.error.email,WrappedArray())))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment