2012-08-16 49 views
10

我正在学习scala和mongodb,并使用该剧!框架,所以当我开始考虑事情时,我会犯各种各样的错误。目前我有一个scala对象,它返回一个通过casbah从mongodb查询返回的数据库对象列表,如下所示:如何将casbah mongodb列表转换为json in scala/play

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的列表转换为JSON输出的正确方法?

编辑:

为清楚起见,我真正想要做的是

val listInJson = collection.find(query).sort(order).toJson 

相当于在同样的方式,我可以写

val listAsString = collection.find(query).sort(order).toString 
+0

你尝试了'Json.toJson ()'功能? (http://www.playframework.org/documentation/2.0.2/ScalaJson) – 2012-08-16 12:27:36

+1

那么为什么你真的需要将数据转换为json?它在数据库中存储为json(真的很好),你真的需要同样的东西吗?我认为你可能只是想根据你想要的结构将数据复制到一个对象中,然后将其序列化为json ... – aishwarya 2012-08-16 12:30:39

+1

我需要将它输出为JSON,以供Web服务使用。 – Roger 2012-08-16 13:37:16

回答

4

我有什么是可怕的解决方案如下;

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

肯定有更好的办法吗?

+0

嘿罗杰,你有没有找到一个更好的方式来转换casbah DBObject来播放JsValue? – teo 2013-07-24 18:32:15

+0

获得'result'后,你将如何将其键值字段填充到映射中? – 2013-09-03 16:46:54

+0

这实际上是一个绝妙的主意!如果表现不重要(例如在漂亮的印刷中它不会),这是完美的。谢谢。 – akauppi 2014-08-28 08:08:23

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

}

7

您可以尝试

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

这应该返回一个JSON阵列快讯