Reputation: 53
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
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:
prettyPrint
ing the JSON can be revisited to fit your needs.Upvotes: 1