Using Casbah, I query Mongo.

val mongoClient = MongoClient("localhost", 27017)
val db = mongoClient("test") 
val coll = db("test")
val results: MongoCursor = coll.find(builder) 

var matchedDocuments = List[DBObject]()
for(result <- results) {
  matchedDocuments = matchedDocuments :+ result
}

Then, I convert the List[DBObject] into JSON via:

val jsonString: String = buildJsonString(matchedDocuments)

Is there a better way to convert from "results" (MongoCursor) to JSON (JsValue)?

private def buildJsonString(list: List[DBObject]): Option[String] = {
  def go(list: List[DBObject], json: String): Option[String] = list match {
     case Nil => Some(json)
     case x :: xs if(json == "") => go(xs, x.toString)
     case x :: xs  => go(xs, json + "," + x.toString)
     case _ => None
  }

  go(list, "")
}
有帮助吗?

解决方案

Assuming you want implicit conversion (like in flavian's answer), the easiest way to join the elements of your list with commas is:

private implicit def buildJsonString(list: List[DBObject]): String =
  list.mkString(",")

Which is basically the answer given in Scala: join an iterable of strings

If you want to include the square brackets to properly construct a JSON array you'd just change it to:

list.mkString("[", ",", "]") // punctuation madness

However if you'd actually like to get to Play JsValue elements as you seem to indicate in the original question, then you could do:

list.map { x => Json.parse(x.toString) }

Which should produce a List[JsValue] instead of a String. However, if you're just going to convert it back to a string again when sending a response, then it's an unneeded step.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top