2016-07-21 2 views
0

BSONArray에서 JSON 텍스트를 가장 빨리 보내는 방법은 무엇입니까?ReactiveMongo Play Framework의 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을 생성하고 수동으로 문자열을 출력하려면 alue를 사용하십시오. 여기

는 당신의 필요에 맞게 사용자 정의 할 수있는 간단한 예입니다

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

위의 응답이다 "하나", "둘", "세"]

당신은 대규모 처리하는 경우 데이터 - Enumerator를 사용하고 응답을 스트리밍하는 것이 더 나을 수도 있습니다.

은 다음을 참조하십시오 https://www.playframework.com/documentation/2.5.x/ScalaStream

+0

휠을 재발 명하는 것처럼 보입니다. – cchantep

관련 문제