11

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
Roger
  • 15,793
  • 4
  • 51
  • 73
  • Did you try the `Json.toJson()` function ? (http://www.playframework.org/documentation/2.0.2/ScalaJson) – ndeverge Aug 16 '12 at 12:27
  • 1
    well why do you really need to convert the data as json ? It is stored as json in db (well bson really), do you really need the same back? i think you may just want to copy data into an object based on your desired structure and then serialize it into json... – aishwarya Aug 16 '12 at 12:30
  • 1
    I need to output it as JSON for a webservice to consume. – Roger Aug 16 '12 at 13:37
  • have you seen http://api.mongodb.org/java/current/com/mongodb/util/JSON.html#serialize(java.lang.Object) ? I wonder if that can work for you... – aishwarya Aug 16 '12 at 15:52
  • @Roger, did you find an elegant solution? – Kevin Meredith Sep 03 '13 at 16:37
  • Looks like reactivemongo is the new way in Play 2.1+ to do JSON ['coast-to-coast'](http://www.playframework.com/documentation/2.1.x/ScalaJsonTransformers). Here is the [sample project](https://github.com/sgodbillon/reactivemongo-tailablecursor-demo) – k.c. sham Nov 05 '13 at 02:44
  • Since the use case was asked, mine is to be able to provide 'pretty printing' of results. AFAIK, MongoDB APIs don't provide any pretty printing of a DBObject. So I'd like to convert to e.g. spray-json and pretty print there. But for raw JSON I'll simply use the DBObject's toString. – akauppi Aug 28 '14 at 08:05

3 Answers3

8

You can try

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

This should return a JSON array with your Alerts

Eric
  • 256
  • 1
  • 3
  • 8
5

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

}

rvbens
  • 51
  • 1
4

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?

Roger
  • 15,793
  • 4
  • 51
  • 73