Created
May 2, 2016 21:10
-
-
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
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
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