Created
July 22, 2021 10:05
-
-
Save import-benjamin/b6a82ddf40e9ad858e2f68072dc8ea30 to your computer and use it in GitHub Desktop.
Marshalling & Unmarshalling json with akka-http and json4s
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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