Skip to content

Instantly share code, notes, and snippets.

@import-benjamin
Created July 22, 2021 10:05
Show Gist options
  • Save import-benjamin/b6a82ddf40e9ad858e2f68072dc8ea30 to your computer and use it in GitHub Desktop.
Save import-benjamin/b6a82ddf40e9ad858e2f68072dc8ea30 to your computer and use it in GitHub Desktop.
Marshalling & Unmarshalling json with akka-http and json4s
name := "json-api-serializer"
version := "0.1"
scalaVersion := "2.13.6"
idePackagePrefix := Some("that.is.a.test")
libraryDependencies ++= Seq(
"com.typesafe.akka" %% "akka-actor-typed" % "2.6.8",
"com.typesafe.akka" %% "akka-stream" % "2.6.8",
"com.typesafe.akka" %% "akka-http" % "10.2.4",
"org.json4s" % "json4s-jackson_2.13" % "4.0.1",
"de.heikoseeberger" % "akka-http-json4s_2.13" % "1.37.0"
)
package that.is.a.test
package apiproject
import akka.actor.typed.scaladsl.Behaviors
import akka.actor.typed.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s.{DefaultFormats, Formats, jackson}
import org.json4s.JsonAST.JValue
import org.json4s.jackson.Serialization
import scala.collection.mutable
import scala.concurrent.ExecutionContextExecutor
object Main extends App with Json4sSupport {
implicit val system: ActorSystem[Nothing] = ActorSystem(Behaviors.empty, "my-system")
implicit val executionContext: ExecutionContextExecutor = system.executionContext
implicit val formats: Formats = DefaultFormats
implicit val serialization: Serialization.type = jackson.Serialization
val queue = new mutable.Queue[JValue]()
val route =
path("home") {
get {
complete {
queue.toList
}
} ~
post {
entity(as[JValue]) { json: JValue =>
complete {
queue.enqueue(json)
json
}
}
} ~
delete {
entity(as[JValue]) { json: JValue =>
complete {
queue.dequeueFirst(_ == json)
json
}
}
}
}
Http().newServerAt("localhost", 8080).bind(route)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment