Constructing Akka HTTP requests for JSON Lines

The doco is fabulous when explaining how to unmarshal a stream of JSON Lines object from an HTTP response using Spray JSON, but I couldn’t find anything on marshaling when constructing a request. I discovered the following approach, but wonder if it is the “blessed” way:

  /*
   * A JsonPrinter that produces compact JSON source without any superfluous whitespace.
   */
  private object JsonLinesCompactPrinter extends CompactPrinter {

    import java.lang.StringBuilder

    override protected def printArray(elements: Seq[JsValue],
                                      sb: StringBuilder): Unit =
      if (sb.length() > 0) {
        sb.append('[')
        printSeq(elements, sb.append(','))(print(_, sb))
        sb.append(']')
      } else {
        printSeq(elements, sb.append('\n'))(print(_, sb))
      }
  }

…and then to use:

    implicit val jsonLinesPrinter: JsonPrinter = JsonLinesCompactPrinter

    Marshal(events).to[RequestEntity]...

Thoughts? Is there a built-in way to do what I’m looking for?

Thanks.

After a couple of years, I learnt that the blessed way with Akka http is to:

    val newline = ByteString("\n")

    implicit val jsonStreamingSupport: JsonEntityStreamingSupport = EntityStreamingSupport
      .json()
      .withFramingRenderer(Flow[ByteString].map(_ ++ newline))
2 Likes