问题 如何在scala / play中将casbah mongodb列表转换为json


我正在学习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

10609
2017-08-16 12:24


起源

你试过吗? Json.toJson() 功能? (playframework.org/documentation/2.0.2/ScalaJson) - nico_ekito
以及为什么你真的需要将数据转换为json?它作为json存储在db(真的是bson)中,你真的需要相同的背面吗?我想你可能只想根据你想要的结构将数据复制到一个对象,然后将其序列化为json ... - aishwarya
我需要将其输出为JSON以供Web服务使用。 - Roger
你见过吗? api.mongodb.org/java/current/com/mongodb/util/... ?我想知道这对你有用吗...... - aishwarya
@Roger,你找到了一个优雅的解决方案吗? - Kevin Meredith


答案:


你可以试试

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

这应该返回带有警报的JSON数组


7
2018-03-19 22:32





我有以下内容

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

}


5
2017-08-30 17:34





我有一个可怕的解决方案如下;

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

肯定有更好的方法吗?


4
2017-08-16 14:32



嘿罗杰,你有没有找到更好的方法将casbah DBObject转换为播放的JsValue? - teo
得到之后 result,您如何将其键值字段填充到地图中? - Kevin Meredith
这实际上是一个绝妙的主意!如果性能无关紧要(例如在漂亮印刷中没有),这是完美的。谢谢。 - akauppi