HTTP: Document how a type is marshalled into json #20514
This commit is contained in:
parent
f974ae984d
commit
e2c1638171
2 changed files with 48 additions and 0 deletions
|
|
@ -0,0 +1,41 @@
|
|||
/*
|
||||
* Copyright (C) 2009-2016 Typesafe Inc. <http://www.typesafe.com>
|
||||
*/
|
||||
package docs.http.scaladsl
|
||||
|
||||
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
|
||||
import akka.http.scaladsl.server.Directives
|
||||
import org.scalatest.{Matchers, WordSpec}
|
||||
|
||||
class SprayJsonCompactMarshalSpec extends WordSpec with Matchers {
|
||||
|
||||
"spray-json example" in {
|
||||
//#example
|
||||
import spray.json._
|
||||
|
||||
// domain model
|
||||
final case class CompactPrintedItem(name: String, id: Long)
|
||||
|
||||
trait CompactJsonFormatSupport extends DefaultJsonProtocol with SprayJsonSupport {
|
||||
implicit val printer = CompactPrinter
|
||||
implicit val compactPrintedItemFormat = jsonFormat2(CompactPrintedItem)
|
||||
}
|
||||
|
||||
// use it wherever json (un)marshalling is needed
|
||||
class MyJsonService extends Directives with CompactJsonFormatSupport{
|
||||
|
||||
// format: OFF
|
||||
val route =
|
||||
get {
|
||||
pathSingleSlash {
|
||||
complete {
|
||||
// should complete with spray.json.JsValue = {"name":"akka","id":42}
|
||||
CompactPrintedItem("akka", 42) // will render as JSON
|
||||
}
|
||||
}
|
||||
}
|
||||
// format: ON
|
||||
//#
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -36,6 +36,13 @@ Once you have done this (un)marshalling between JSON and your type ``T`` should
|
|||
.. includecode:: ../../code/docs/http/scaladsl/SprayJsonExampleSpec.scala
|
||||
:include: example
|
||||
|
||||
4. By default, spray-json marshals your types to pretty printed json by implicit conversion using PrettyPrinter, as defined in
|
||||
``implicit def sprayJsonMarshallerConverter[T](writer: RootJsonWriter[T])(implicit printer: JsonPrinter = PrettyPrinter): ToEntityMarshaller[T]``.
|
||||
Alternately to marshal your types to compact printed json, bring a ``CompactPrinter`` in scope to perform implicit conversion.
|
||||
|
||||
.. includecode:: ../../code/docs/http/scaladsl/SprayJsonCompactMarshalSpec.scala
|
||||
:include: example
|
||||
|
||||
To learn more about how spray-json works please refer to its `documentation <https://github.com/spray/spray-json>`_.
|
||||
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue