0

Play 2.2.1, scala 2.10

// PersonModel.scala
case class PersonModel(name: String, age: Long)

object PersonModel2 {    

  implicit object PersonModelFormat extends Format[PersonModel] {
    def reads(json: JsValue): PersonModel = PersonModel(
      (json \ "name").as[String],
      (json \ "age").as[Long])
    def writes(u: PersonModel): JsValue = JsObject(List(
      "name" -> JsString(u.name),
      "age" -> JsNumber(u.age)))
  }

sbt says

[error] PersonModel.scala:15: overriding method reads in trait Reads of type (json: play.api.libs.json.JsValue)play.api.libs.json.JsResult[models.PersonModel];
[error]  method reads has incompatible type
[error]     def reads(json: JsValue): PersonModel = PersonModel(
[error]         ^
1
  • 2
    To explain why you get the error: the compiler is actually telling you that you are trying to override the method reads (defined in the Reads trait) returning a different type than the one defined. You should return a JsResult[PersonModel]. Hence, you can just wrap your call to the PersonModel constructor with a JsSuccess(PersonModel(..., ...)) and change the return type of the method! Commented Nov 22, 2013 at 10:05

3 Answers 3

4

In this case, since you're not doing fancy things with the output json (like changing the key names in the resulting json object), I'd go for:

case class PersonModel(name: String, age: Long)

import play.api.libs.json._
implicit val personModelFormat = Json.format[PersonModel]

This way, you can, for example

scala> val j = PersonModel("julien", 35)
j: PersonModel = PersonModel(julien,35)
scala> println(Json.toJson(j))
{"name":"julien","age":35}

More info can be found here

HTH,

Julien

Sign up to request clarification or add additional context in comments.

Comments

2

Things have changed in recent versions, I'd say for the better. In 2.2.x, you'd do it this way, using the new functional syntax and combinators:

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


 implicit val PersonModelFormat: Format[PersonModel] = (
     (__ \ "name").format[String] and
     (__ \ "age").format[Long]
 )(PersonModel.apply, unlift(PersonModel.unapply))

Much shorter!

The documentation for 2.2.x http://www.playframework.com/documentation/2.2.1/ScalaJsonCombinators provides a good explanation for the rationale for the change.

Comments

0

For single usage there is an inline solution:

Json.writes[PersonModel].writes(personModelInstance)  // returns JsObject

From documentation:
macro-compiler replaces Json.writes[User] by injecting into compile chain the exact code you would write yourself

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.