Scala, Scalatra, Gson, and JSON - Convert a JSON String to a Scala object with Gson

While working on a Scalatra web service recently, I decided to use JSON pass my data into a REST POST method, and within that POST method I decided to turn the JSON String back into an object using the Google Gson library. This was a little tricky, and kept throwing an exception until I realized that the Scalatra params.get method was returning a Scala Some reference instead of the plain String I was expecting.

Given that little bit of background, here's how I used the Gson library in my Scala/Scalatra project to convert a JSON String to a Scala object:

  /**
   * Use this Scala case class to give Gson a class/object to convert the JSON back into.
   */
  case class Dude(firstName: String, lastName: String, age: Int)

  /**
   * String looks like this:
   * 
   * {"firstName":"Leonard","lastName":"Nimoy","age":81}
   * 
   */
  post("/posttest") {
    val jsonString = params.get("JSON")
    try {
        println("CONVERTING JSON BACK TO OBJECT")
        val gson = new Gson
        // jsonString is actually a Some, need to use get() here
        val dude = gson.fromJson(jsonString.get, classOf[Dude])
        println("FNAME: " + dude.firstName)
        println("LNAME: " + dude.lastName)
    } catch {
        case e: Exception => e.printStackTrace
        case _ => println
    }
  }