Encoding JSON with Circe

There are many Scala libraries to manipulate JSON, so why did we choose Circe?

Circe is a very clean JSON framework with good performance, but the real reason we have chosen it is that Circe provides a complete documentation, with an explanation of all of the principles used to play with JSON. Circe uses Cats underneath, which we used in Chapter 3, Handling Errors. Cats is a library from Typelevel. Typelevel is a community that is extremely kind to newcomers in functional programming. It provides lots of great documentation; you can check it out at https://typelevel.org/. In fact, if you wish to dig deeper into functional programming, this is the place to start! The downside of Circe is the number of transitive dependencies; hence, it is fine to use it in a server application, but it might be a little heavy if you want a smaller footprint.

In order to integrate Circe with Play, we can use the integration done by Jilen at https://github.com/jilen. We have already added the dependency to our template, but for reference, the following needs to be added to libraryDependencies, in build.sbt:

libraryDependencies += "com.dripower" %% "play-circe" % "2609.0"

Then, we need to add the Circe trait to our controller, as follows:

class WebServices @Inject()(cc: ControllerComponents, productDao: ProductsDao) extends AbstractController(cc) with Circe

We will import the required classes, as follows:

import play.api.libs.circe.Circe
import io.circe.generic.auto._
import io.circe.syntax._

We are almost there; we need to replace .mkstring(",") with .asJson. That's it!

The final code is as follows:

def listProduct() = Action.async { request =>
  val futureProducts = productDao.all()
    for(
      products <- futureProducts
    ) yield (Ok(products.asJson))
}

Now we can run APISpec; we should have your first working test for the API!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset