Skip to content

Instantly share code, notes, and snippets.

@hhanh00
Created November 9, 2015 15:26
Show Gist options
  • Save hhanh00/d6c33829157511208c81 to your computer and use it in GitHub Desktop.
Save hhanh00/d6c33829157511208c81 to your computer and use it in GitHub Desktop.
How to make a custom marshaller for JSON API
case class MyData(id: String, d: Int)
object MyData {
implicit def dataMarshaller: ToEntityMarshaller[MyData] = {
Marshaller.StringMarshaller.wrap(MediaTypes.`application/vnd.api+json`)(data => {
val jo = JsObject("data" ->
JsObject("type" -> JsString("dashboard"), "id" -> JsString(data.id),
"attributes" -> JsObject("exposure" -> JsNumber(data.d)))
)
jo.compactPrint
})
}
}
object Server extends App with SprayJsonSupport {
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
implicit val ec = system.dispatcher
import MyData._
val route =
path("api" / "dashboards" / Segment) { date =>
get {
complete {
MyData("1", 10000)
}
}
}
val bindingFuture = Http().bindAndHandle(route, "0.0.0.0", 4100)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment