Skip to content

Instantly share code, notes, and snippets.

@pjan
Created May 6, 2014 03:06
Show Gist options
  • Save pjan/f2c5187b367c8791a432 to your computer and use it in GitHub Desktop.
Save pjan/f2c5187b367c8791a432 to your computer and use it in GitHub Desktop.
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