user3561400
user3561400

Reputation: 53

scala akka-http - complete get request with a pre-built json object and stream it

I am trying to complete a get request by returning a pre-built JsonArray, and also find a way to stream it. I can easily complete the request without any errors and return Json if I convert the JsonArray to string, like so:

get {
  path("getJsonData") {
    parameterMap {
      params =>
        complete(HttpEntity(ContentTypes.`application/json`, myJsonArray.toString))
    }
  }
}

However, I would like to avoid converting to string, and be able to stream the JsonArray, because the resulting JsonArray can be very large in some cases.

JsonArray is created from scratch from individual JsonObjects, and I do not use case classes, so I could not use the standard approaches I found in the documentation.

I am new to Akka Http and not sure if there is a simple way to solve this problem, would appreciate some help.

Upvotes: 2

Views: 441

Answers (1)

Stefano Bonetti
Stefano Bonetti

Reputation: 9023

With the below you will be streaming each element of your JSON array in a separate HTTP chunk.

      complete(HttpEntity(ContentTypes.`application/json`, 
        Source(myJsonArray.elements).map(j ⇒ ByteString(j.prettyPrint))))

Note that:

  • The choice of prettyPrinting the JSON can be revisited to fit your needs.
  • You can adjust the size of your frame by batching elements together using the Akka Streams API.

Upvotes: 1

Related Questions