Scala case classes, Gson, Json object deserialization, and Scalatra

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.

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.