1

I am working on a small project try to get a Scala/Play backend working. I am trying to have it return and also process JSON on the web service side. I cannot seem to figure out how to get the JSON marshalling and unmarshalling to work. Could someone help me with this issue? I am using Play 2.1 and Scala 2.10. The error that I get is "overriding method reads in trait Reads of type (json: play.api.libs.json.JsValue)play.api.libs.json.JsResult[models.Address]; method reads has incompatible type"

  • Edited. Someone else gave me the solution. For read you must use JsSuccess, not JsResult.

    case class Address(id: Long, name: String)
    
    object Address {
    
    implicit object AddressFormat extends Format[Address] {
    def reads(json: JsValue):Address = JsSuccess(Address(
        (json \ "id").as[Long],
        (json \ "name").as[String]
    ))
    
    def writes(address: Address): JsValue = JsObject(Seq(
        "id" -> JsNumber(address.id),
        "name" -> JsString(address.name)
    ))
    }
    }
    
0

3 Answers 3

3

With Play 2.1 you could simplify your code:

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

implicit val addressFormat = (
  (__ \ "id").format[String] and
  (__ \ "name").format[Long]
)(Address.apply, unlift(Address.unapply))

More detailed information can be found here: ScalaJsonCombinators

2

You can simplify your code even further by using macros, although they are marked as experimental:

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

case class Address(id: Long, name: String)

implicit val addressFormat = Json.format[Address]

More details on this technique in the official Play documentation.

0

Hey my solution would be:

import play.api.libs.json.JsonNaming.SnakeCase
import play.api.libs.json._

object Test {

  implicit val config = JsonConfiguration(SnakeCase)
  implicit val userFormat: OFormat[Test] = Json.format[Test]

}

case class Test(
                 testName: String,
                 testWert: String,
                 testHaus: String
               )

In conclusion, you get a compenion object. The config converts all keys of the case class into snakecase. The implicit values ensure that a valid Json can be parsed into a model. So you get your test model back.

The Json should look like this:

{
    "test_name" : "Hello",
    "test_wert": "Hello",
    "test_haus": "Hello"
}

https://www.playframework.com/documentation/2.6.x/ScalaJsonAutomated

1
  • Oh i didnt realized that your're using play 2.1, it might wont work, im sry. Im using 2.6 and its quite simpler Commented Jan 12, 2018 at 21:32

Not the answer you're looking for? Browse other questions tagged or ask your own question.