简体   繁体   中英

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

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 .

According to this post, a more correct way to implement Reads[T] in Play 2.1 would be:

implicit val productReads: Reads[Product] = (
    (__ \ "ean").read[Long] and
    (__ \ "name").read[String] and
    (__ \ "description").read[String]
)(Product.apply _)

And don't forget additional imports:

import play.api.libs.functional.syntax._ 
import play.api.libs.json._

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM