what fastest way return json text bsonarray?
i'm returning big json document. possible omit processing play
jsvalue
now i'm returning this:
val result:bsonarray = .... ok(json.tojson(result))
i think faster like:
ok(result.totextjson).as(mimetypes.json)
update here full code:
val command = json.parse( s""" { "aggregate": "$collection", "pipeline": [ { "$$match": { "$$and" : [ { "${rootattrs.time}" : { "$$gt": $startsectime }}, { "${rootattrs.time}" : { "$$lt": $endsectime }}, { "${rootattrs.command}" : { "$$eq": ${tocmd(command.gps_coordinates)} }} ] }}, { "$$sort": { "${rootattrs.time}" : 1 }}, { "$$limit": $max_gps_all_data }, { "$$project" : { "_id":0, "${rootattrs.time}":1, "${rootattrs.command}":1, "${rootattrs.value}":1, "${rootattrs.ignition}":1, "${rootattrs.sim_number}":1 } } ]}""") db.command(rawcommand(bsondocumentformat.reads(command).get)).map { out => out.get("result").map { case result: bsonarray => logger.debug("loaded gps history data size: " + result.length) ok(json.tojson(result)) // <- need return json, parsing jsvalue can take time case _ => logger.error("result gps history data not array") badrequest }.getorelse(badrequest) }
you can bypass step of creating intermediary jsvalue if want create own writeable, , output string more manually.
here simple example can customised need
val result: bsonarray = bsonarray("one", "two", "three") def convertbsonarraytostring(jsval: bsonarray): array[byte] = { // method assumes have bsonarray of strings (which may not) var strs: stream[string] = jsval.stream.map(_.get match { case s: bsonstring => s.value }) var json: string = strs.mkstring("[\"", "\",\"", "\"]") json.getbytes() } implicit def writeableof_bsonarray: writeable[bsonarray] = { writeable(convertbsonarraytostring ,some("application/json")) } def dostuff = action { results.ok(result) }
the response above ["one","two","three"]
if dealing massive data - may better off using enumerator, , streaming response.
see: https://www.playframework.com/documentation/2.5.x/scalastream
Comments
Post a Comment