2012-08-16 108 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陣列快訊