How to convert casbah mongodb list to json in scala / play

∥☆過路亽.° 提交于 2019-11-29 01:52:55

You can try

com.mongodb.util.JSON.serialize(Alerts.list())

This should return a JSON array with your Alerts

I have the following

def service() = Action {
 // connect
 val collection = MongoConnection()("someDB")("someCollection")
 // simply convert the result to a string, separating items with a comma
 // this string goes inside an "array", and it's ready to hit the road
 val json = "[%s]".format(
  collection.find(someQuery).toList.mkString(",")
 )

 Ok(json).as("application/json")

}

I have what is a horrid solution as follows;

val currentAlerts = Alerts.list()

var jsonList : List[JsValue] = Nil

// Iterate over the DBObjects and use to String to convert each to JSON
// and then parse that back into the list so we can use toJson on it later.
// MAD, but works.

for (dbObject <- currentAlerts) {
    jsonList ::=  Json.parse(dbObject.toString)
}

val result = Json.toJson(jsonList)
Ok(result).as("application/json")

There must surely be a better way?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!