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?