Giter Club home page Giter Club logo

play-circe's Introduction

Circe support for playframework

Build codecov

How to get it

  • Add dependency

For play 2.6.x

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

For play 2.7.x

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

For play 2.8.x

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

For play 3.0.x

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

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 ignores the configured HttpErrorHandler and just uses DefaultHttpErrorHandler. If this not what you want, simply make a trait to override circeErrorHandler like this
class MyController @Inject() (val errorHandler: HttpErrorHandler, val controllerComponents: ControllerComponents) extends BaseController with Circe {
  override def circeErrorHandler = errorHandler
}

play-circe's People

Contributors

aaabramov avatar aeons avatar djx314 avatar easel avatar felixbr avatar github-actions[bot] avatar jilen avatar leonardehrenfried avatar mcornejo avatar migiside avatar nikolajmobilab avatar scala-steward avatar zy4 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

play-circe's Issues

Exception when decoding fail.

I got this obscure exception when the decoding is not possible ( in this case cause there is a laking field)

play.api.http.HttpErrorHandlerExceptions$$anon$1: Execution exception[[anon$2: Attempt to decode value on failed cursor: El(DownField(noscript),false,false)]]
    at play.api.http.HttpErrorHandlerExceptions$.throwableToUsefulException(HttpErrorHandler.scala:280)
    at play.api.http.DefaultHttpErrorHandler.onServerError(HttpErrorHandler.scala:206)
    at play.core.server.netty.PlayRequestHandler$$anonfun$2$$anonfun$apply$1.applyOrElse(PlayRequestHandler.scala:100)
    at play.core.server.netty.PlayRequestHandler$$anonfun$2$$anonfun$apply$1.applyOrElse(PlayRequestHandler.scala:99)
    at scala.concurrent.Future$$anonfun$recoverWith$1.apply(Future.scala:346)
    at scala.concurrent.Future$$anonfun$recoverWith$1.apply(Future.scala:345)
    at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32)
    at play.api.libs.iteratee.Execution$trampoline$.execute(Execution.scala:70)
    at scala.concurrent.impl.CallbackRunnable.executeWithValue(Promise.scala:40)
    at scala.concurrent.impl.Promise$DefaultPromise.tryComplete(Promise.scala:248)
    at scala.concurrent.Promise$class.complete(Promise.scala:55)
    at scala.concurrent.impl.Promise$DefaultPromise.complete(Promise.scala:153)
    at scala.concurrent.Future$$anonfun$flatMap$1.apply(Future.scala:251)
    at scala.concurrent.Future$$anonfun$flatMap$1.apply(Future.scala:251)
    at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32)
    at akka.dispatch.BatchingExecutor$AbstractBatch.processBatch(BatchingExecutor.scala:55)
    at akka.dispatch.BatchingExecutor$BlockableBatch$$anonfun$run$1.apply$mcV$sp(BatchingExecutor.scala:91)
    at akka.dispatch.BatchingExecutor$BlockableBatch$$anonfun$run$1.apply(BatchingExecutor.scala:91)
    at akka.dispatch.BatchingExecutor$BlockableBatch$$anonfun$run$1.apply(BatchingExecutor.scala:91)
    at scala.concurrent.BlockContext$.withBlockContext(BlockContext.scala:72)
    at akka.dispatch.BatchingExecutor$BlockableBatch.run(BatchingExecutor.scala:90)
    at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:39)
    at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:409)
    at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
Caused by: io.circe.DecodingFailure$$anon$2: Attempt to decode value on failed cursor: El(DownField(noscript),false,false)

The parsing code

Action.async(circe.json[String => Site])  ...

How to use the module circe-generic-extras?

Hi,

I am currently running into a problem with decoding/encoding an ATD that should work as an enum attribute in one of my model case classes.

My "enum":

sealed trait BettingTopic
case object Bitcoin extends BettingTopic
case object Ethereum extends BettingTopic

my model looks like this:

final case class Bet(... topic: BettingTopic ...)

After some research I looked into circes deriveEnumerationDecoder/deriveEnumerationEncoder that comes along with the circe's "generic extras" module. This could solve my problem, but by default it is not included in play-circe.

The necessary import would be:

import io.circe.generic.extras.semiauto._

Is there any chance to make this work?

You can find the link to that here:

Thank you a lot!
BG

Logger class conflicts with any other defined Logger class in 2814.1

Upon upgrading from play-circe 2812.0 to 2814.1, the following code generates the following error:

CODE:

import play.api.libs.circe.Circe
import play.api.mvc.{AbstractController, Action, AnyContent, ControllerComponents, Result, Results}
import javax.inject.Inject
import com.typesafe.scalalogging.StrictLogging
import scala.concurrent.ExecutionContext

class SampleController @Inject() (
cc: ControllerComponents,
)(implicit ec: ExecutionContext)
extends AbstractController(cc)
with StrictLogging
with Circe {
}

ERROR:

class SampleController inherits conflicting members:
protected val logger: com.typesafe.scalalogging.Logger (defined in trait StrictLogging) and
protected val logger: play.api.Logger (defined in trait Logging)
(note: this can be resolved by declaring an override in class ListingsController.)]
at play.sbt.PlayExceptions$CompilationException$.apply(PlayExceptions.scala:34)
at play.sbt.PlayExceptions$CompilationException$.apply(PlayExceptions.scala:34)
at scala.Option.map(Option.scala:230)
at play.sbt.run.PlayReload$.$anonfun$taskFailureHandler$1(PlayReload.scala:42)
at scala.Option.map(Option.scala:230)
at play.sbt.run.PlayReload$.taskFailureHandler(PlayReload.scala:37)
at play.sbt.run.PlayReload$.compileFailure(PlayReload.scala:30)
at play.sbt.run.PlayReload$.$anonfun$compile$3(PlayReload.scala:65)
at scala.util.Either$LeftProjection.map(Either.scala:573)
at play.sbt.run.PlayReload$.compile(PlayReload.scala:65)

Scala 2.12

Would love to have support for this in scala 2.12!
Thanks

public release?

hi.
I'd like to use circe in play.
is there any public release for your solution? bintray?

Play 2.6.x

Hi, is play-circe compatible with Play 2.6.0-M2? I understand 2.6.x is not stable as of yet but it'd be nice if we can try it out with play-circe.

see faulty JSON when decode fails?

Hi peeps,

I'm blessed with very, um, fluid clients that often generate wrong JSON bodies for API requests, and I spend too much time realizing and then demonstrating this, mostly using sledgehammers like ngrep.

Circe decoder errors like "Attempt to decode value on failed cursor: El(DownField(whatever),false,false)]]" tells me what field failed but not enough about why. I've been mucking around looking for a play-circe-friendly way to log the original request body when decoding fails, but I'm stumped. BodyParsers seem to bail the moment they fail and I can't find a reasonable way to see the request body by composing actions, adding filters, etc.

In my dreams I glue a Logger.error of the json string onto https://github.com/jilen/play-circe/blob/master/src/main/scala/play/api/libs/circe/Circe.scala line 36 but I can't figure out how to do it short of forking the whole thing and then I lose out on mooching off your efforts. :) Any thoughts?

Thanks!

  • Henry

Automatically Get `play.api.libs.json.Reads` and `Writes` via `circe`?

Given a case class with > 22 fields, i.e. playframework/playframework#1141 (comment), as I understand, I need to manually build the Reads[X] and Writes[X] - http://stackoverflow.com/a/28168370/409976. I'd prefer to automatically get them, vis-a-vis scala - parse json of more than 22 elements into case class in circe.

However, I'd prefer to keep using play json since my entire project uses it, rather than circe. Is it possible to do:

import play.api.libs.json.{Reads, Writes}

case class MoreThan22Fields(x1: String, x2: Int, ..., x40: Boolean)
def f(x: MoreThan22Fields): Reads[MoreThan22Fields] = ???
def g(x: MoreThan22Fields): Writes[MoreThan22Fields] = ???

where the ??? definition is replaced by the functions, respectively:

MoreThan22Fields => CirceJsonDecoder[MoreThan22Fields] => Reads[MoreThan22Fields]
MoreThan22Fields => CirceJsonEncoder[MoreThan22Fields] => Writes[MoreThan22Fields]

Note that my understanding is:

encode : Object -> JSON
decode : JSON  -> Object

In short, I'd like to use the power of circe per > 22 field case classes, but I'd like to use Play's Reads and Writes.

How can I do this?

2609.0 artifact issues

It appears as if the 2609.0 artifacts weren't completely rebuild - perhaps no make clean prior to publishing?

With the artifacts from maven central, I get binary incompatibility errors like this:

Uncaught error from thread [application-akka.actor.default-dispatcher-18]: cats.syntax.package$show$.toShowOps(Ljava/lang/Object;Lcats/Show;)Lcats/Show$Ops;, shutting down JVM since 'akka.jvm-exit-on-fatal-error' is enabled for ActorSystem[application]
java.lang.NoSuchMethodError: cats.syntax.package$show$.toShowOps(Ljava/lang/Object;Lcats/Show;)Lcats/Show$Ops;
	at play.api.libs.circe.Circe.onCirceError(Circe.scala:23)

With the master branch built as a snapshot, everything works.

Any chance of a version bump, clean, and republish?

Consider adding a BodyWritable[Json] type class instance

With the update to Play 2.6 my Play WS clients broke.

Previously body serialization when calling put, post, etc. worked using play.api.http.Writable and type class instances writableOf_Json in Circe.scala did the job.

Now play-ws requires a type class play.api.libs.ws.BodyWritable which is not included in this project. See https://www.playframework.com/documentation/2.6.x/WSMigration26#Scala

For now I defined this trait in my project which does the job:

trait CirceJsonBodyWritables {

  val defaultPrinter = Printer.noSpaces

  implicit def bodyWritableOf_Json(
      implicit printer: Printer = defaultPrinter): BodyWritable[Json] = {
    BodyWritable(
      json => InMemoryBody(ByteString.fromString(json.pretty(printer))),
      "application/json")
  }

}

Would be nice to add this to the Circe.scala trait but it requires you to add play-ws dependency.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.