hseeberger / akka-http-json Goto Github PK
View Code? Open in Web Editor NEWIntegrate some of the best JSON libs in Scala with Akka HTTP
License: Apache License 2.0
Integrate some of the best JSON libs in Scala with Akka HTTP
License: Apache License 2.0
http://search.maven.org/#search|ga|1|akka-http-play-json
The latest version on there is 1.10.1.
Would you be so kind as to publish them?
Thanks!
Hi guys, maybe I'm missing something so I'd like to confirm it's actually a bug. If I modify the example app from the repo, changing the routes like below to include a formField route:
private def route(implicit mat: Materializer) = {
import Directives._
import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport._
import io.circe.generic.auto._
pathSingleSlash {
post {
entity(as[Foo]) { foo =>
complete {
foo
}
}
}
} ~
path("formurlencoded") {
post {
formFields('coolKey) { coolKey =>
complete(s"The cool value is '${coolKey}'")
}
}
}
}
If I run and test it with the added route:
curl -d "coolKey=coolValue" -X POST http://localhost:8000/formurlencoded
I get the following error:
The request's Content-Type is not supported. Expected: application/json or multipart/form-data
But if I remove all circe/json related code like in the following:
private def route(implicit mat: Materializer) = {
import Directives._
// import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport._
// import io.circe.generic.auto._
//
pathSingleSlash {
post {
complete {
"no json :("
}
}
} ~
path("formurlencoded") {
post {
formFields('coolKey) { coolKey =>
complete(s"The cool value is '${coolKey}'")
}
}
}
}
And test it again with:
curl -d "coolKey=coolValue" -X POST http://localhost:8000/formurlencoded
I get the expected response:
The cool value is 'coolValue'
Does this look like a bug to you or am I missing something?
Thanks
Hi,
I'm trying to write a rejection handler that will customise the json response in case more than one field is wrong.
The problem is that ErrorAccumulatingUnmarshaller is private, therefore I cannot pattern match on it
private val rejectionHandler: RejectionHandler = RejectionHandler.newBuilder()
.handle {
case r@MalformedRequestContentRejection(message, cause) =>
val errors: List[String] = cause match {
// Single error - This happens when mixing in FailFastCirceSupport
case DecodingFailure(msg, ops) =>
ops.map {
case DownField(key) => s"Invalid format for field: ${key}"
case o => s"An error has occurred: $o"
}
// Multiple errors - This happens when mixing in ErrorAccumulatingCirceSupport
// I would like to pattern match but I can't because ErrorAccumulatingUnmarshaller is private
// case e:ErrorAccumulatingUnmarshaller.DecodingFailures =>
case e =>
List("an unexpected error has happened " + e.getMessage)
}
complete(BadRequest, errors.mkString("\n"))
}.result()
Is there another way to achieve that? If not, is there a reason for it to be private?
Thanks,
Paolo
I think the @return
should read:
marshaller for `T`
(instead of marshaller for any Json value
)
As found in http://danielasfregola.com/2016/02/07/how-to-build-a-rest-api-with-akka-http/comment-page-1/#comment-236
The confusion:
Unfortunately, Akka Http resolves complete(Future(())) with an http response with code 200 and empty body — same as complete(Future(None))! Please, put a comment below if you know the rationale behind this design choice.
The reason: http://danielasfregola.com/2016/02/07/how-to-build-a-rest-api-with-akka-http/comment-page-1/#comment-236
It picks up de.heikoseeberger.akkahttpjson4s.Json4sSupport#json4sMarshaller
for Unit
as well, causing unexpected outcome. I see it may be tough to change the types around given how this works here but worth pointing out or thinking about perhaps.
Hi there,
are there any more complete usage examples for using this to integrate json marshalling for newbies like me?
Thanks!
Recently a new package called "extras" was released for Circe, it contains interesting new features like Configurable Generic Derivation and I was wondering if there is any plan to add support for these new features in this fantastic library.
Thank you.
hi.
Full disclosure: I'm a n00b Scala developer so please bear with me.
I'm running into an issue where the deserialization doesn't seem to be "fast" enough when trying to debug under an IDE (IntelliJ)...basically the code looks like this (I'm using Json4sSupport
):
post {
entity(as[ModuleListRequest]) { m =>
complete {
// ...
ModuleListResponseType(status = Some(1))
}
}
}
which runs fine when using sbt run
or just "Run" under IntelliJ and works beautifully. However, as soon as run this under a debugger (even without any breakpoints), it doesn't work in the sense that the unmarshalling to ModuleListRequest
does not complete (will eventually get an HTTP 400 failure because the input is "not recognized".
If i replace entity with the native as[JObject]
it's fine and i can unmarshall manually but obviously defeating the purpose of using an automagic unmarshaller.
Not sure if this is an issue using this library or Akka HTTP itself or it's "by design". some clues/guidance will be greatly appreciated. :)
Current version is not compatible (as expected)
root[ERROR] java.lang.NoSuchMethodError: akka.http.scaladsl.unmarshalling.Unmarshaller$.byteStringUnmarshaller(Lakka/stream/Materializer;)Lakka/http/scaladsl/unmarshalling/Unmarshaller;
root[ERROR] at de.heikoseeberger.akkahttpplayjson.PlayJsonSupport$class.playJsValueUnmarshaller(PlayJsonSupport.scala:44)
In the last release of Circe (0.6) there are some breaking changes in the API, that makes it incompatible with akka-http-json.
java.lang.NoSuchMethodError: io.circe.jawn.package$.decode(Ljava/lang/String;Lio/circe/Decoder;)Lcats/data/Xor;
at de.heikoseeberger.akkahttpcirce.CirceSupport$$anonfun$circeUnmarshaller$1.apply(CirceSupport.scala:56)
at de.heikoseeberger.akkahttpcirce.CirceSupport$$anonfun$circeUnmarshaller$1.apply(CirceSupport.scala:54)
at akka.http.scaladsl.unmarshalling.Unmarshaller$EnhancedFromEntityUnmarshaller$$anonfun$mapWithCharset$extension$1.apply(Unmarshaller.scala:96)
at akka.http.scaladsl.unmarshalling.Unmarshaller$EnhancedFromEntityUnmarshaller$$anonfun$mapWithCharset$extension$1.apply(Unmarshaller.scala:96)
at akka.http.scaladsl.unmarshalling.Unmarshaller$EnhancedUnmarshaller$$anonfun$mapWithInput$extension$1$$anonfun$apply$16$$anonfun$apply$17$$anonfun$apply$18.apply(Unmarshaller.scala:88)
at akka.http.scaladsl.util.FastFuture$$anonfun$map$extension$1.apply(FastFuture.scala:23)
at akka.http.scaladsl.util.FastFuture$$anonfun$map$extension$1.apply(FastFuture.scala:23)
at akka.http.scaladsl.util.FastFuture$.akka$http$scaladsl$util$FastFuture$$strictTransform$1(FastFuture.scala:41)
at akka.http.scaladsl.util.FastFuture$.transformWith$extension1(FastFuture.scala:45)
at akka.http.scaladsl.util.FastFuture$.map$extension(FastFuture.scala:23)
at akka.http.scaladsl.unmarshalling.Unmarshaller$EnhancedUnmarshaller$$anonfun$mapWithInput$extension$1$$anonfun$apply$16$$anonfun$apply$17.apply(Unmarshaller.scala:88)
at akka.http.scaladsl.unmarshalling.Unmarshaller$EnhancedUnmarshaller$$anonfun$mapWithInput$extension$1$$anonfun$apply$16$$anonfun$apply$17.apply(Unmarshaller.scala:88)
at akka.http.scaladsl.unmarshalling.Unmarshaller$$anon$1.apply(Unmarshaller.scala:55)
at akka.http.scaladsl.unmarshalling.LowerPriorityGenericUnmarshallers$$anonfun$messageUnmarshallerFromEntityUnmarshaller$1$$anonfun$apply$1$$anonfun$apply$2.apply(GenericUnmarshallers.scala:25)
at akka.http.scaladsl.unmarshalling.LowerPriorityGenericUnmarshallers$$anonfun$messageUnmarshallerFromEntityUnmarshaller$1$$anonfun$apply$1$$anonfun$apply$2.apply(GenericUnmarshallers.scala:25)
at akka.http.scaladsl.unmarshalling.Unmarshaller$$anon$1.apply(Unmarshaller.scala:55)
at akka.http.scaladsl.server.directives.MarshallingDirectives$$anonfun$entity$1$$anonfun$apply$1.apply(MarshallingDirectives.scala:34)
at akka.http.scaladsl.server.directives.MarshallingDirectives$$anonfun$entity$1$$anonfun$apply$1.apply(MarshallingDirectives.scala:34)
at akka.http.scaladsl.server.directives.FutureDirectives$$anonfun$onComplete$1$$anonfun$apply$1.apply(FutureDirectives.scala:37)
at akka.http.scaladsl.server.directives.FutureDirectives$$anonfun$onComplete$1$$anonfun$apply$1.apply(FutureDirectives.scala:35)
at akka.http.scaladsl.server.directives.BasicDirectives$$anonfun$textract$1$$anonfun$apply$5.apply(BasicDirectives.scala:153)
at akka.http.scaladsl.server.directives.BasicDirectives$$anonfun$textract$1$$anonfun$apply$5.apply(BasicDirectives.scala:153)
at akka.http.scaladsl.server.directives.BasicDirectives$$anonfun$mapRouteResult$1$$anonfun$apply$3.apply(BasicDirectives.scala:60)
at akka.http.scaladsl.server.directives.BasicDirectives$$anonfun$mapRouteResult$1$$anonfun$apply$3.apply(BasicDirectives.scala:60)
at akka.http.scaladsl.server.directives.BasicDirectives$$anonfun$textract$1$$anonfun$apply$5.apply(BasicDirectives.scala:153)
at akka.http.scaladsl.server.directives.BasicDirectives$$anonfun$textract$1$$anonfun$apply$5.apply(BasicDirectives.scala:153)
at akka.http.scaladsl.server.directives.OnSuccessMagnet$$anon$1$$anonfun$1$$anonfun$apply$4$$anonfun$apply$5.apply(FutureDirectives.scala:97)
at akka.http.scaladsl.server.directives.OnSuccessMagnet$$anon$1$$anonfun$1$$anonfun$apply$4$$anonfun$apply$5.apply(FutureDirectives.scala:97)
at akka.http.scaladsl.util.FastFuture$.akka$http$scaladsl$util$FastFuture$$strictTransform$1(FastFuture.scala:41)
at akka.http.scaladsl.util.FastFuture$$anonfun$transformWith$extension1$1.apply(FastFuture.scala:51)
at akka.http.scaladsl.util.FastFuture$$anonfun$transformWith$extension1$1.apply(FastFuture.scala:50)
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)
pretty please :)
I'm using version 1.15.0
of akka-http-json and 0.7.1
of circe.
By default the ContentType of a response is set to application/json
, meaning that the client doesn't know which charset to use and has trouble displaying e.g. umlauts. I'd like to be able to set the charset or have a sensible default like utf-8. Right now when I write a very simple application that does nothing but respond with a JSON:
case class Foo(s: String)
import io.circe.generic.auto._
import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport._
val route =
path("hello") {
get {
complete(Foo("München"))
}
}
And I send a Request to such a Server with the following Headers:
GET /hello HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
DNT: 1
Accept-Charset: utf-8
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,de;q=0.6
I receive the following response:
HTTP/1.1 200 OK
Content-Length: 16
Content-Type: application/json
Date: Wed, 12 Apr 2017 14:02:10 GMT
Server: akka-http/10.0.5
{
"s": "München"
}
I would expect the Response header to include charset=utf-8
.
We could very easily just set the Response to utf-8 by default. I could even create a PR if desired.
I would like to use this with play default JsObject but not sure if this is possible. This is what i have been trying but getting the message:
could not find implicit value for parameter um.
val json = Unmarshal(response).to[JsObject]
Are there any default unmarshallers for JsObject and if not how could I make this my selfe?
There are no artifacts in the maven central nor in bintray repos for scala 2.11 with versions greater than 2.17.0
Hi,
I’m using the Play JSON module. If unmarshalling fails, it throws a JsResultException
, which results in a MalformedRequestContentRejection
. However the rejection only contains the stringified message of the exception, e.g. the object available to a rejection handler is something like
MalformedRequestContentRejection(
"JsResultException(errors:List((/foo,List(ValidationError(List(error.path.missing),WrappedArray())))))",
None
)
This prevents one from using the information contained in the exception in any meaningful way, e.g. to construct a pretty response for the client. The reason that the information is not available is this code in Akka:
case Failure(x: IllegalArgumentException) ⇒ reject(ValidationRejection(x.getMessage.nullAsEmpty, Some(x)))
case Failure(x) ⇒ reject(MalformedRequestContentRejection(x.getMessage.nullAsEmpty, Option(x.getCause)))
So basically there are three ways to make the actual list of validation errors available in a rejection handler: either JsResultException
should be wrapped in some other exception (so that it’s extracted by x.getCause
), or a different exception subclassing IllegalArgumentException
should be thrown, or both. Here’s an approach that worked for me:
In PlayJsonSupport
:
def read(json: JsValue) = reads.reads(json).recoverTotal { error =>
throw new IllegalArgumentException { initCause(JsResultException(error.errors)) }
}
In a rejection handler:
implicit val rejectionHander = RejectionHandler.newBuilder()
.handle { case ValidationRejection(_, Some(e)) ⇒ /* `e.getCause` is the `JsResultException` */ ??? }
.result()
Do you think this change in PlayJsonSupport
makes sense? If so, something similar needs to be done with Json.parse(input)
to allow handling parsing errors. I haven’t used the other modules, but I imagine they can benefit from similar changes. If this makes sense (rather than, say, changing the behavior of unmarshalling directives themselves), I can submit a PR with these changes, at least for Play JSON.
Circe now seems to be very interesting and actively developing JSON library.
I've seen at least one implementation can be used here if @koshelev wouldn't mind.
Please :)
Hi, thx for this very useful lib!
sbt-updates seems to find an new version that I cannot find anywhere in the repo.
dependencyUpdates
[info] Found 1 dependency update for pim-indexer
[info] de.heikoseeberger:akka-http-circe : 1.19.0-M1 -> 1.19.0-M2
$curl https://github.com/hseeberger/akka-http-json/releases/tag/v1.19.0-M2
Not Found
Is it an hidden release? 😁
Right now circe-spray includes some features that akka-http-circe doesn't, such as error accumulation, which allows you to easily create an error response that includes all errors in e.g. form input (see the circe-spray demo for an example).
What do you think, @hseeberger—would you be okay with adding that here as well?
Could you publish the Scala 2.10 versions of the 1.4.2
modules?
Things like joda's DateTime, or java's URI don't unmarshal well with CirceSupport. For example, if I have a case class that has a DateTime field, I get the following error:
could not find implicit value for parameter um: akka.http.scaladsl.unmarshalling.FromRequestUnmarshaller[com.ecommerce.inventory.api.RequestViews.AcknowledgeShipmentView]
(AcknowledgeShipment
has an expectedDate
field of type org.joda.time.DateTime
)
It seems that once a route has JSON support enabled with akka-http-json4s (and possibly with the alternatives too) it is no longer to POST to it with the standard content types, application/x-www-form-urlencoded
and multipart/form-data
, only application/json
is allowed.
For example, the following route definition:
import akka.http.scaladsl.server.{ Directives, Route }
object TestRoutes extends Directives {
def routes: Route =
path("test") {
formFields('name) { name =>
complete(s"Hello $name")
}
}
}
can be posted to with cURL as follows:
$ curl -i -d 'name=foo' 'http://localhost/test'
HTTP/1.1 200 OK
Server: akka-http/10.0.9
Date: Thu, 24 Aug 2017 08:35:22 GMT
Content-Type: text/plain; charset=UTF-8
Content-Length: 9
Hello foo
But, once akka-http-json4s is introduced:
import akka.http.scaladsl.server.{ Directives, Route }
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s.DefaultFormats
import org.json4s.native.Serialization
object TestRoutes extends Directives with Json4sSupport {
implicit val formats = DefaultFormats
implicit val serialization = Serialization
def routes: Route =
path("test") {
formFields('name) { name =>
complete(s"Hello $name")
}
}
}
we can no longer POST to it in the same way:
$ curl -i -d 'name=foo' 'http://localhost/test'
HTTP/1.1 415 Unsupported Media Type
Server: akka-http/10.0.9
Date: Thu, 24 Aug 2017 08:37:44 GMT
Content-Type: text/plain; charset=UTF-8
Content-Length: 71
The request's Content-Type is not supported. Expected:
application/json
Is this by design or necessity? It seems to me that ideally it would be best to be able to enable JSON support on a route without disabling any built-in functionality of akka-http.
I see that there has been progress on this but I unfortunately can't access the errors, nor have the pretty printing in the most recent version.
Does any one else experiences an issue with extremely long compilation time?
I created small project with akka-http-json (particularly Circe) to show up a problem: https://github.com/chuwy/compile-problem/blob/master/src/main/scala/me.chuwy/example/Routes.scala#L10
If I remove CirceSupport
from code, it compiles in a few seconds, but with import CirceSupport._
or extends CirceSupport
it takes ~100s on this simple code chunk and >5min on more complicated. And all this even without actual decoding/encoding.
4e2ba10 removed the ability to provide a custom JsValue => String
function into the Play JSON marshaller and hard-coded it to be pretty printed. In my primary application for this, a marshaller that forcibly injects large amounts of excess whitespace into every request and response is not suitable.
This change wasn't made to others like the json4s marshaller, which still accepts a parameter to choose whether or not you want pretty printing.
I can make a pull request reverting this particular part of that change if that would be helpful? If you're not interested in restoring this, please let me know so I can go ahead with writing my own marshaller.
(Incidentally, I always thought it was a strange choice to default to using pretty-printed formatting. This is not what I'd expect from a library meant for real applications.)
akka-http 10.0.0 supports Scala 2.11. akka-http-play-json 1.11.0 should be released for Scala 2.11 so that people can upgrade akka-http without getting an eviction warning.
Hi everyone, using this directive in routes
encodeResponseWith(Gzip) {
...
}
produce this error:
io.circe.ParsingFailure: expected json value got � (line 1, column 1)
when executing this line:
Unmarshal(httpResponse.entity).to[...]
This is because the response is encoded with gzip so it is an Array[Byte] and the Unmarshaller is expecting a ByteString
I could manage to overcome using this function to unzip the response:
/**
* Unzip and return the String-JSON representation in this Array[Byte]
*/
def unzip(compressed: Array[Byte]): Either[Throwable, String] =
Try {
val inputStream = new GZIPInputStream(new ByteArrayInputStream(compressed))
scala.io.Source.fromInputStream(inputStream).mkString
}.toEither
And defining this Unmarshaller:
implicit def circeCompressUnMarshaller[A](implicit decoder: Decoder[A]): FromEntityUnmarshaller[A] =
Unmarshaller.byteArrayUnmarshaller.map(
unzip(_).flatMap(jawn.decode[A]).fold(throw _, identity)
)
But I dont know if this is the right solution and it can be added to this repo.
Thank you @hseeberger
Hi,
I am using akka-http-circe and getting the following error:
Error:(53, 83) could not find implicit value for parameter um: akka.http.scaladsl.unmarshalling.Unmarshaller[akka.http.scaladsl.model.ResponseEntity,com.msilb.scalanda.restapi.Response.AccountDetailsResponse]
getWithQueryParams(s"accounts/$accountId").flatMap(r => Unmarshal(r.entity).to[AccountDetailsResponse])
Here is the code excerpt where it fails:
import de.heikoseeberger.akkahttpcirce.CirceSupport._
def getAccountDetails(accountId: AccountId): Future[AccountDetailsResponse] = {
import io.circe.generic.auto._
getWithQueryParams(s"accounts/$accountId").flatMap(r => Unmarshal(r.entity).to[AccountDetailsResponse])
}
AccountDetailsResponse
is a case class which contains nested case classes and case objects. I am thinking circe fails to find implicit decoders for the given domain model but unfortunately the error message does not tell me which value it fails to decode, otherwise I could provide it manually. Is there any way to add this information to the error message?
Circe equivalent issue of #135
We've just upgraded most of our stack to 2.11 and see that your latest release (1.12.0) is not published in Maven Central. We've not migrated any of our projects to Scala 2.12 yet and is a sizable effort so it will not come quickly.
Can you please continue to publish releases to Maven Central for Scala 2.11?
It would be nice to also have kind of "debug mode" where I will be able to unmarshal to a tuple (mycaseclass, jsonString)
The NoContentException
exception is defined by akka-http and is used by unmarshallers to signal the entity was unexpectedly empty.
The current behaviour in the different sub-projects is to let the underlying library to fail. It means a poor exception with no integration with akka-http (something like Unexpected end of input
).
The NoContentException
exception is already used in directives to handle nicely this error. For example the entity()
directive will reject the request with RequestEntityExpectedRejection
.
Note that the empty entity can never be a valid json value. If null
is expected the string null
must be in the entity and is not the same as an empty one.
This change could possibly break user code as the exception in case of empty entity won't be the same.
Hi,
I migrated to the new akka-http-json version, and now looks like that with the new import
import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport._
and import io.circe.generic.extras.auto._
my code is not compiling and I am getting:
could not find implicit value for parameter encoder
however when I replaced it with import io.circe.generic.auto._
, the code compiles.
Any know issues ?
thanks,
Even it's a Java library:)
Can you publish a version for scala 2.12.0-RC1? :)
Hi,
Thanks for project, it's pretty useful. I wonder why this is not part of the io.circe lib?
They have very similar lib for spray, it would be great to have some, or at least the akka-http there. (https://github.com/travisbrown/circe/tree/master/spray/src/main/scala/io/circe/spray)
Have you tried to fork io.circe and push some of these libs?
Thanks,
Tamas
I have a simple program (inspired by a sample from another blog) that receives data to a POST request at JSON, and works fine when I use the json4s variant. However when I run the same requests into a version of the app that uses the Hakka-http-json I see an unmarshalling exception when unmarshalling a JSON array.
I'd expect equivalent behaviour in both examples, so I suspect something is missing in either my code, documentation, or elsewhere?
Json4s:
$ curl -X POST -H 'Content-Type: application/json' -d '[{"name": "Julie-ann", "age": 21}, {"name": "George", "age": 22}]' http://localhost:8080/customers
"Added 2 customers\n
$ curl http://localhost:8080/customers
[{"name":"Julie-ann","age":21},{"name":"George","age":22}]
Jackson:
$ curl -X POST -H 'Content-Type: application/json' -d '[{"name": "Julie-ann", "age": 21}, {"name": "George", "age": 22}]' http://localhost:8080/customers
There was an internal server error
Server:
[info] Running com.example.JacksonHttpApp
Press RETURN to stop...
[INFO] [08/09/2017 15:54:40.459] [JacksonHttpApp-akka.actor.default-dispatcher-3] [akka.actor.ActorSystemImpl(JacksonHttpApp)] Server online at http://localhost:8080/
[ERROR] [08/09/2017 15:54:44.851] [JacksonHttpApp-akka.actor.default-dispatcher-6] [akka.actor.ActorSystemImpl(JacksonHttpApp)] Error during processing of request: 'scala.collection.immutable.Map$Map2 cannot be cast to com.example.JacksonHttpApp$Customer'. Completing with 500 Internal Server Error response. To change default exception handling behavior, provide a custom ExceptionHandler.
java.lang.ClassCastException: scala.collection.immutable.Map$Map2 cannot be cast to com.example.JacksonHttpApp$Customer
at scala.collection.immutable.List.foreach(List.scala:389)
at com.example.JacksonHttpApp$.$anonfun$routes$4(AkkaJacksonParsing.scala:27)
at akka.http.scaladsl.server.directives.RouteDirectives.$anonfun$complete$1(RouteDirectives.scala:47)
...
Progs attached here...
progs.zip
Happy Holidays everyone! :)
probably a basic scala question rather than akka-http-json
specific...but i'm trying to use this with a RejectionHandler
and i don't know of an elegant way to use Json4sSupport
or if it's even possible. Would like to have some guidance.
thanks!
Currently there is no way to parameterise the json4sMashaller
to make it print pretty JSON. Such output is sometimes useful it printing information for manual inspection.
Json4sSupport.json4sMarshaller
depends on an implicit Serialization
, which defines the printing method (either write
or writePretty
), so parameterising it the same way as playJsonMarshaller
is impossible. Do you have an idea how this could be elegantly done?
How to parse JSON that uses snake case to case class and generate JSON output using snake case?
Let's say my DTO looks like
case class User(firstName: String, lastName: String)
Once Scala 2.11.6 has been "properly" released, remove temporary resolver from build.
I was thinking with the right import
import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport._
I should be able to say:
.withEntity(
MyCaseClassForWhichIHaveACirceEncoder(7, "Hi")
)
On an HttpRequest
. But I can't.
I am currently working on a PR for this project and I found the newly added formatter very rigid.
Would it be possible to change some settings like for example the --maxColumn
to something like 100 or 120.
Also the following code snippet:
???.recover( _ ⇒ _ ⇒ {
case MappingException("unknown error", ite: InvocationTargetException) ⇒
throw ite.getCause
})
is formatted to:
???.recover(
_ ⇒
_ ⇒ {
case MappingException("unknown error",
ite: InvocationTargetException) ⇒
throw ite.getCause
}
)
which I personally don't find very readable. What's your opinion on this?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.