简体   繁体   中英

How to convert case class to JSON in Play framework 2.3.x (Scala)?

Anyone can show me how to convert case class class instances to JSON in Play framework (particularly Play v2.3.x) with Scala?

For example I have code like this:

case class Foo(name: String, address: String)

def index = Action {
      request => {
        val foo = Foo("John Derp", "Jem Street 21")  // I want to convert this object to JSON
        Ok(Json.toJson(foo))    // I got error at here
      }
}

The error message:

Cannot write an instance of com.fasterxml.jackson.data bind.JsonNode to HTTP response. Try to define a Writeable[com.fasterxml.jackson.databind.JsonNode]

UPDATE: I found out the above error is caused by wrong import of the Json class, it should be: import play.api.libs.json.Json . However I still got error on implicit problem below.

I have read this tutorial , but when I tried the implicit Writes[Foo] code:

  implicit val fooWrites: Writes[Foo] = (
        (JsPath \ "name").write[String] and
            (JsPath \ "address").write[String]
        )(unlift(Foo.unapply))

I got Can't resolve symbol and and Can't resolve symbol unlift error in Intellij. Also the tutorial's code looks complex just for the conversion of an object to JSON. I wonder if there is more simple way to do this?

You can get an Writes[Foo] instance by using Json.writes :

implicit val fooWrites = Json.writes[Foo]

Having this implicit in scope is all you need to convert Foo to JSON. See the documetnation here and here for more info about JSON reads/writes.

The second problem - Can't resolve symbol and - is an Intellij bug introduced in version 1.3 of the Scala plugin. In version 1.3.3 of the Scala plugin, there's now a workaround - set preference checkbox:

Languages & Frameworks > Scala > Core (default) tab > Use old implicit search algorithm

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