Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JannikArndt/a493725eb67c2efcdd4119e2bb0ccff1 to your computer and use it in GitHub Desktop.
Save JannikArndt/a493725eb67c2efcdd4119e2bb0ccff1 to your computer and use it in GitHub Desktop.
Akka Http Json4s Unmarshalling - Minimal Example in Scala
import akka.http.scaladsl.model.ContentTypes.`application/json`
import akka.http.scaladsl.model.HttpEntity
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.testkit.ScalatestRouteTest
import de.heikoseeberger.akkahttpjson4s.Json4sSupport._
import org.json4s.native.Serialization
import org.json4s.{DefaultFormats, _}
import org.scalatest._
final case class Timestamp(ts: Long)
object TimestampRoute {
implicit val serialization: Serialization.type = native.Serialization
implicit val formats: DefaultFormats.type = DefaultFormats
val timestampRoute: Route = {
post {
extractRequest { request =>
print(s"Incoming request: $request \n\n")
entity(as[Timestamp]) { timestamp =>
complete {
print(s"Parsed Timestamp=$timestamp \n\n")
timestamp
}
}
}
}
}
}
class RequestParsing extends WordSpec with Matchers with BeforeAndAfter with ScalatestRouteTest {
"Route" should {
"parse timestamp" in {
val input = """{"ts":1513159031181}"""
val request = HttpEntity(`application/json`, input.getBytes())
Post("/", request) ~> TimestampRoute.timestampRoute ~> check {
print(s"Response: $response \n\n")
val payload = response.entity.toString.stripPrefix("HttpEntity.Strict(application/json,").stripSuffix(")")
payload shouldEqual input
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment