Circe support for playframework
- Add repository
resolvers += "Bintary JCenter" at "http://jcenter.bintray.com"
- Add dependency
For play 2.5.x
libraryDependencies += "play-circe" %% "play-circe" % "2.5-0.7.0"
For play 2.4.x
libraryDependencies += "play-circe" %% "play-circe" % "2.4-0.7.0"
package play.api.libs.circe
import io.circe.generic.auto._
import io.circe.syntax._
import play.api._
import play.api.mvc._
object CirceController extends Controller 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)
}
}
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(dropNullKeys = true)