mbrush
mbrush

Reputation: 11

JSON Rendering Scala/Play 2.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"

Upvotes: 1

Views: 2155

Answers (3)

Max Günther
Max Günther

Reputation: 27

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

Upvotes: 0

pjay_
pjay_

Reputation: 135

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.

Upvotes: 2

EECOLOR
EECOLOR

Reputation: 11244

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

Upvotes: 3

Related Questions