0

从 BSONArray 返回 JSON 文本的最快方法是什么?

我正在返回非常大的 JSON 文档。是否可以省略处理Play JsValue

现在我像这样返回:

 val result:BSONArray = ....
 Ok(Json.toJson(result))

我认为更快的是:

 Ok(result.toTextJSON).as(MimeTypes.JSON)

在这里更新我的完整代码:

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 all GPS history data size: " + result.length)
      Ok(Json.toJson(result)) // <- I need just return JSON, parsing to JsValue can take some time

    case _ =>
      Logger.error("Result GPS history data not array")
      BadRequest

  }.getOrElse(BadRequest)
}
4

1 回答 1

-1

如果你想创建自己的Writeable,你可以绕过创建中间JsValue的步骤,更多地手动输出字符串。

这是一个简单的示例,可以根据您的需要进行定制

val result: BSONArray = BSONArray("one", "two", "three")

def convertBsonArrayToString(jsval: BSONArray): Array[Byte] = {
  // this method assumes I have a BSONArray of Strings (which you 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)
}

上面的响应是 ["one","two","three"]

如果您正在处理大量数据 - 您最好使用 Enumerator 并流式传输响应。

见:https ://www.playframework.com/documentation/2.5.x/ScalaStream

于 2016-07-23T14:14:37.563 回答