circe for play
Clone or download
jilen Merge pull request #54 from zy4/patch-1
bump circeV to 0.10.1
Latest commit 64cdfb0 Nov 16, 2018
Permalink
Failed to load latest commit information.
project use codeacy Sep 27, 2018
src fix codeacy issues Sep 27, 2018
.gitignore add test cases Nov 8, 2015
.travis.yml use plain text project token Sep 30, 2018
LICENSE Create LICENSE Sep 25, 2017
README.md update version and codeacy Sep 27, 2018
build.sbt bump circeV to 0.10.1 Nov 14, 2018
version.sbt Setting version to 2610.1-SNAPSHOT Sep 25, 2018

README.md

Circe support for playframework

Build Status Codacy Badge Codacy Badge

How to get it

  • Add dependency

For play 2.6.x

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

Usage

package play.api.libs.circe

import io.circe.generic.auto._
import io.circe.syntax._
import play.api._
import play.api.mvc._

class CirceController(val controllerComponents: ControllerComponents) extends BaseController with Circe {

  case class Bar(bar: Int)
  case class Foo(foo: String, bar: Bar)

  val bar = Bar(1)
  val foo = Foo("foo", bar)

  //serve json
  def get = Action {
    Ok(foo.asJson)
  }

  //parse json to case class
  def post = Action(circe.json[Foo]) { implicit request =>
    val isEqual = request.body == foo
    Ok(isEqual.toString)
  }

  def postJson = Action(circe.json) { implicit request =>
    val isEqual = request.body == foo.asJson
    Ok(isEqual.toString)
  }

  def postTolerate = Action(circe.tolerantJson[Foo]) { implicit request =>
    val isEqual = request.body == foo
    Ok(isEqual.toString)
  }

  def postTolerateJson = Action(circe.tolerantJson) { implicit request =>
    val isEqual = request.body == foo.asJson
    Ok(isEqual.toString)
  }
}

FAQ

  • If you want to customize the json output, you can provide an implicit Printer in scope (default is Printer.noSpaces):
import io.circe.Printer

implicit val customPrinter = Printer.spaces2.copy(dropNullValues = true)
  • The Circe totally ignore the configured HttpErrorHandler and just use DefaultHttpErrorHandler. If this not what you want, simply make an trait to override circeErrorHandler like this
class MyController @Inject() (val errorHandler: HttpErrorHandler, val controllerComponents: ControllerComponents) extends BaseController with Circe {
  override def circeErrorHandler = errorHandler
}