How to convert POJO to JSON in Play Framework 2.3.x (Scala)?

Can anyone show me how to convert a POJO or class instance to JSON in the Play platform (especially Play v2.3.x) using Scala?

For example, I have a 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 } } 

Error message:

Unable to write an instance of com.fasterxml.jackson.data bind.JsonNode for an HTTP response. Try defining Writeable [com.fasterxml.jackson.databind.JsonNode]

UPDATE: I found that the above error was caused by improper import of the Json class, it should be: import play.api.libs.json.Json . However, I still got the error with the implicit issue below.

I 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 the error Can't resolve symbol and and Can't resolve symbol unlift in Intellij. Also, the tutorial code looks complicated only for converting an object to JSON. I wonder if there is an easier way to do this?

+6
source share
2 answers

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

 implicit val fooWrites = Json.writes[Foo] 

Having this implicit scope is all you need to convert Foo to JSON. See the documentation here and here for more information on reading / writing JSON.

+7
source

The second problem, Can't resolve symbol and , is an Intellij bug introduced in version 1.3 of the Scala plugin. Scala plugin version 1.3.3 now has a workaround option - set the prefix:

Languages ​​and frameworks> Scala> Core tab (default)> Use the old implicit search algorithm

+1
source

Source: https://habr.com/ru/post/980651/


All Articles