spray-json Support
The SprayJsonSupport trait provides a Marshaller
and Unmarshaller
for every type T
that an implicit
spray.json.RootJsonReader
and/or spray.json.RootJsonWriter
(respectively) is available for.
Just mix in spray.httpx.SprayJsonSupport
or import spray.httpx.SprayJsonSupport._
.
For example:
import spray.json.DefaultJsonProtocol
import spray.httpx.unmarshalling._
import spray.httpx.marshalling._
import spray.http._
import HttpCharsets._
import MediaTypes._
case class Person(name: String, firstName: String, age: Int)
object MyJsonProtocol extends DefaultJsonProtocol {
implicit val PersonFormat = jsonFormat3(Person)
}
import MyJsonProtocol._
import spray.httpx.SprayJsonSupport._
import spray.util._
val bob = Person("Bob", "Parr", 32)
val body = HttpEntity(
contentType = ContentType(`application/json`, `UTF-8`),
string =
"""|{
| "name": "Bob",
| "firstName": "Parr",
| "age": 32
|}""".stripMarginWithNewline("\n")
)
marshal(bob) === Right(body)
body.as[Person] === Right(bob)
If you bring an implicit spray.json.JsonPrinter
into scope the marshaller will use it. Otherwise it uses the
default spray.json.PrettyPrinter
.
Note
Since spray-httpx only comes with an optional dependency on spray-json you still have to add it to your project yourself. Check the spray-json documentation for information on how to do this.