16

I'm trying to serialize some relatively simple models into json. For example, I'd like to get the json representation of:

case class User(val id: Long, val firstName: String, val lastName: String, val email: Option[String]) {
    def this() = this(0, "","", Some(""))
}

Do i need to write my own Format[User] with the appropriate reads and writes methods or is there some other way? I've looked at https://github.com/playframework/Play20/wiki/Scalajson but I'm still a bit lost.

acjay
  • 34,571
  • 6
  • 57
  • 100
LuxuryMode
  • 33,401
  • 34
  • 117
  • 188

2 Answers2

24

Yes, writing your own Format instance is the recommended approach. Given the following class, for example:

case class User(
  id: Long, 
  firstName: String,
  lastName: String,
  email: Option[String]
) {
  def this() = this(0, "","", Some(""))
}

The instance might look like this:

import play.api.libs.json._

implicit object UserFormat extends Format[User] {
  def reads(json: JsValue) = User(
    (json \ "id").as[Long],
    (json \ "firstName").as[String],
    (json \ "lastName").as[String],
    (json \ "email").as[Option[String]]
  )

  def writes(user: User) = JsObject(Seq(
    "id" -> JsNumber(user.id),
    "firstName" -> JsString(user.firstName),
    "lastName" -> JsString(user.lastName),
    "email" -> Json.toJson(user.email)
  ))
}

And you'd use it like this:

scala> User(1L, "Some", "Person", Some("s.p@example.com"))
res0: User = User(1,Some,Person,Some(s.p@example.com))

scala> Json.toJson(res0)
res1: play.api.libs.json.JsValue = {"id":1,"firstName":"Some","lastName":"Person","email":"s.p@example.com"}

scala> res1.as[User]
res2: User = User(1,Some,Person,Some(s.p@example.com))

See the documentation for more information.

botchniaque
  • 4,698
  • 3
  • 35
  • 63
Travis Brown
  • 138,631
  • 12
  • 375
  • 680
9

Thanks to the fact User is a case class you could also do something like this:

implicit val userImplicitWrites = Json.writes[User]
val jsUserValue = Json.toJson(userObject)

without writing your own Format[User]. You could do the same with reads:

implicit val userImplicitReads = Json.reads[User]

I haven't found it in the docs, here is the link to the api: http://www.playframework.com/documentation/2.2.x/api/scala/index.html#play.api.libs.json.Json$

Paweł Kozikowski
  • 1,025
  • 2
  • 11
  • 23
  • Just for completeness - without using implicits: `Json.reads[User].reads(myJson).get` – User Jun 29 '15 at 09:39
  • 1
    This one should now be marked as the answer. Here's the link for the updated doc: https://www.playframework.com/documentation/2.5.x/ScalaJsonAutomated – Gustavo Maloste Oct 19 '16 at 18:12