diff --git a/akka-docs/rst/scala/code/docs/http/scaladsl/SprayJsonCompactMarshalSpec.scala b/akka-docs/rst/scala/code/docs/http/scaladsl/SprayJsonCompactMarshalSpec.scala new file mode 100644 index 0000000000..5b296821ab --- /dev/null +++ b/akka-docs/rst/scala/code/docs/http/scaladsl/SprayJsonCompactMarshalSpec.scala @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2009-2016 Typesafe Inc. + */ +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 + //# + } + } +} diff --git a/akka-docs/rst/scala/http/common/json-support.rst b/akka-docs/rst/scala/http/common/json-support.rst index 893c3fd8d1..5c3aab6c47 100644 --- a/akka-docs/rst/scala/http/common/json-support.rst +++ b/akka-docs/rst/scala/http/common/json-support.rst @@ -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 `_.