By Alvin Alexander. Last updated: June 6, 2016
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.