Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm learning scala and mongodb at present and using the play! framework, so I'm making all sorts of mistakes as I get my head around things. Currently I have a scala object that returns a list of database objects returned from a mongodb query via casbah as follows;

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
   }

... }

Elsewhere in my code I wish to output the List of objects in Json - so I have;

  val currentAlerts = Alerts.list()

What I'd like to write is something like;

  val resultingJson = currentAlerts.toJson 

But when I do this, I understandably get the following error;

  value toJson is not a member of List[com.mongodb.casbah.Imports.DBObject]

My question is - what's the right way to convert a List of com.mongodb.casbah.Imports.DBObject into Json for output?

EDIT:

For clarity, what I really want to do is the equivalent of

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

In the same way that I CAN write

val listAsString = collection.find(query).sort(order).toString
like image 271
Roger Avatar asked Aug 16 '12 12:08

Roger


3 Answers

You can try

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

This should return a JSON array with your Alerts

like image 174
Eric Avatar answered Nov 10 '22 03:11

Eric


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

}

like image 30
rvbens Avatar answered Nov 10 '22 03:11

rvbens


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?

like image 21
Roger Avatar answered Nov 10 '22 04:11

Roger