From a MongoDB collection to Scala object array through Gson to JSON

I used the following code to convert an array of Scala objects on the server into a JSON string that I could return back to the client. So it's going from a MongoDB collection to an array of Scala objects through Gson to become a JSON string.

/**
 * Return a list of all stored sticky notes as a JSON string.
 */
get("/getStickyNotes") {
  var notes = ArrayBuffer[StickyNote]()
  val coll = getMongoDbCollection
  val dbObjects = coll.find
  for (dbObject <- dbObjects) {
    notes += convertDbObjectToStickyNote(dbObject)
  }
  // return array as json
  (new Gson).toJsonTree(notes.toArray)
}

def convertDbObjectToStickyNote(o: MongoDBObject): StickyNote = {
  val content = o.getAs[String]("content")
  val windowTitle = o.getAs[String]("windowTitle")
  val fontSizeIncrement = o.getAs[Int]("fontSizeIncrement")
  return StickyNote(content.get, windowTitle.get, fontSizeIncrement.get)
}

A few notes:

  • The actual code is longer than this; I trimmed it down to make it easier to read here.
  • I used gson.toJsonTree in this code, but I may have been able to use just gson.toJson. I started using toJsonTree because of an unrelated problem.
  • If I was a cooler Scala programmer I'd probably use a collection method like flatMap instead of a for loop to create the notes object form dbObjects.
  • Notice the need to use .get when I return the StickyNote in the second to last line of code. That's because I'm dealing with Some references.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.