Deserialize a JSON array using Gson, Scala, Scalatra, and a Scala case class

Here's an example of how I deserialize an array of objects encoded in JSON, in this case using Scalatra and Scala:

import scala.collection.JavaConversions._

/**
 * This method expects to receive Array[StickyNote].
 */
post("/saveStickyNote") {
  val json = params.get("STICKY_NOTE")
  val gson = new Gson
  try {

    // (1) convert the json string to an array of StickyNote
    val jsonString = json.get

    // (2) jsonString is actually a Some, need to use get() here (should also test for None)
    val stickyNotes = gson.fromJson(jsonString, classOf[Array[StickyNote]])

    // (3) do whatever you want with your object array
    for (stickyNote <- stickyNotes) {
      println("CONTENT: " + stickyNotes.content)
    }

  } catch {
    case e: Exception => e.printStackTrace
    case _ => println
  }
}

To get this to work, I've defined a StickyNote case class here on the server side, and Gson does a great job of converting properly formatted JSON into an array of StickyNote objects.

If you were using Gson with Java to deserialize a JSON array, your code would look very similar. The major change would be that your Java code in the gson.fromJson line would look something like this:

val stickyNotes = gson.fromJson(jsonString, StickyNote[].class)

I'm not sure what the exact syntax should be there, but I think that's right, or hopefully close enough to get you started if you're using Java.