Created
December 13, 2017 12:51
-
-
Save JannikArndt/a493725eb67c2efcdd4119e2bb0ccff1 to your computer and use it in GitHub Desktop.
Akka Http Json4s Unmarshalling - Minimal Example in Scala
This file contains hidden or 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
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