Search code examples
jsonscalaplayframework-2.0jacksonplayframework-json

Serialize objects with Play Scala api and Json


I try to serialize my models in a play 2.0 application with Scala to Json. This is how my code looks like:

package models

import play.api.libs.json._

case class Task(id: Long, label: String, date: String)

object Task {

  ...

  implicit object TaskFormat extends Format[Task] {
    def reads(json: JsValue): Task = Task(
      (json \ "id").as[Long],
      (json \ "label").as[String],
      (json \ "date").as[String])

    def writes(t: Task): JsValue = JsObject(Seq(
      "id" -> JsNumber(t.id),
      "label" -> JsString(t.label),
      "date" -> JsString(t.date)))
  }
}

Unfortunartly I get the following error when running the application:

verriding method reads in trait Reads of type (json: play.api.libs.json.JsValue)play.api.libs.json.JsResult[models.Task]; method reads has incompatible type

I didn't yet find a solution. The documentation of the api (http://www.playframework.org/documentation/api/2.0/scala/play/api/libs/json/package.html) seems to suggest the approach I've taken as well.

Does anybody spot my mistake?

Many thanks,
Joel


Solution

  • The error message tells you what the problem is: the return type must be

    play.api.libs.json.JsResult[models.Task]
    

    So it looks to me like you are returning the Task directly, not wrapping it in a JsResult.

    I don't use Play, but this is what the compiler is trying to tell you.

    So, given that, what is the issue? If you look at the Play 2.0 documentation, it says reads returns a T. But if you look at the GitHub source you find that it was changed to JsResult[T] as of August 21, 2012.

    So you're using a newer version than the one people have written advice for.

    I'm not sure whether the newer API is online, but you can browse the JSON source here.