2016-07-21 66 views
0

什么是从BSONArray返回JSON文本的最快方法?在Play框架中返回ReactiveMongo JSON

我返回非常大的JSON文档。是否可以省略处理PlayJsValue

现在,我回来是这样的:

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) 
} 
+0

您能否在此处添加更全面的代码示例? – marcospereira

回答

-1

您可以绕过创建中介JsV的步骤如果你想创建你自己的Writeable,并且手动输出字符串。

下面是一个简单的例子可以自定义您的需要

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) 
} 

上面的反应是[“一”,“二”,“三”]

如果你正在处理大量的数据 - 您最好还是使用枚举器,然后流式传输响应。

请参阅:https://www.playframework.com/documentation/2.5.x/ScalaStream

+0

它看起来像我重新发明轮子。 – cchantep