Created
May 6, 2014 03:06
-
-
Save pjan/f2c5187b367c8791a432 to your computer and use it in GitHub Desktop.
This file contains hidden or 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.json._ | |
import play.api.libs.functional.syntax._ | |
case class User(id: Int, name: String, partner: Option[String]) | |
// Json format without null | |
val userReads: Reads[User] = ( | |
(JsPath \ "id").read[Int] and | |
(JsPath \ "name").read[String] and | |
(JsPath \ "partner").readNullable[String] | |
)(User.apply _) | |
val userWrites: Writes[User] = ( | |
(JsPath \ "id").write[Int] and | |
(JsPath \ "name").write[String] and | |
(JsPath \ "partner").writeNullable[String] | |
)(unlift(User.unapply)) | |
val userFormat: Format[User] = Format(userReads, userWrites) | |
// Json format with null | |
val userReadsNull: Reads[User] = ( | |
(JsPath \ "id").read[Int] and | |
(JsPath \ "name").read[String] and | |
(JsPath \ "partner").read[Option[String]] | |
)(User.apply _) | |
val userWritesNull: Writes[User] = ( | |
(JsPath \ "id").write[Int] and | |
(JsPath \ "name").write[String] and | |
(JsPath \ "partner").write[Option[String]] | |
)(unlift(User.unapply)) | |
val userFormatNull: Format[User] = Format(userReadsNull, userWritesNull) | |
// demo time | |
val user1 = User(123, "John", Some("Mary")) | |
val user2 = User(123, "Peter", None) | |
Json.toJson(user1)(userFormat) | |
Json.toJson(user2)(userFormat) | |
Json.toJson(user1)(userFormatNull) | |
Json.toJson(user2)(userFormatNull) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment