By Alvin Alexander. Last updated: June 6, 2016
I was able to get Gson to work with Scala and Scalatra very easily. Here's a sample Scalatra POST method where I receive a JSON string and convert it to a StickyNote case class object:
post("/saveStickyNote") { val json = params.get("STICKY_NOTE") val gson = new Gson try { // jsonString is actually a Some, need to use get() here val stickyNote = gson.fromJson(json.get, classOf[StickyNote]) // i can now call methods on my stickyNote object println("CONTENT: " + stickyNote.content) // do whatever you need to with the stickyNote object ... } catch { case e: Exception => e.printStackTrace case _ => println } }
Gson and Scala also work very easily with arrays of JSON objects, like this:
val notes = gson.fromJson(json.get, classOf[Array[StickyNote]])
I can share more information about my StickyNote object later, but it's just a basic Scala case class, nothing major.