Rog*_*ger 11 scala mongodb playframework casbah
我正在学习scala和mongodb并使用该剧!框架,所以当我理解事物时,我犯了各种各样的错误.目前我有一个scala对象,它返回一个通过casbah从mongodb查询返回的数据库对象列表,如下所示;
object Alerts  {
   def list() : List[DBObject]= {
        val collection = MongoDatabase.collection;
        val query = MongoDBObject.empty
        val order = MongoDBObject("Issue Time:" -> -1)
        val list = collection.find(query).sort(order).toList
        list
   }
...}
在我的代码的其他地方,我希望输出Json中的对象列表 - 所以我有;
  val currentAlerts = Alerts.list()
我想写的是这样的;
  val resultingJson = currentAlerts.toJson 
但是当我这样做时,我可以理解得到以下错误;
  value toJson is not a member of List[com.mongodb.casbah.Imports.DBObject]
我的问题是 - 将com.mongodb.casbah.Imports.DBObject的List转换为Json输出的正确方法是什么?
编辑:
为清楚起见,我真正想做的就是相当于
val listInJson = collection.find(query).sort(order).toJson
就像我写的一样
val listAsString = collection.find(query).sort(order).toString
你可以试试
com.mongodb.util.JSON.serialize(Alerts.list())
这应该返回带有警报的JSON数组
小智 5
我有以下内容
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")
}
我有一个可怕的解决方案,如下所示;
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")
一定有更好的方法吗?
| 归档时间: | 
 | 
| 查看次数: | 5621 次 | 
| 最近记录: |