Create a JSON object (String) with GSON and Scala (or Java)

Here's a quick example of how to create a JSON object (String, technically) using the Google Gson library and Scala. Note that this is very easily converted to Java:

import com.google.gson.Gson

/**
 * This is the rough equivalent of a Java POJO class.
 */
case class Person(firstName: String, lastName: String, age: Int)

/**
 * Create a JSON object (string) using Scala and Gson.
 */
object GsonPojoTest {
  
  def main(args: Array[String]) {
    val spock = new Person("Leonard", "Nimoy", 81)
    val gson = new Gson
    println(gson.toJson(spock))
  }

}

If you run this Scala object, the JSON output looks like this:

{"firstName":"Leonard","lastName":"Nimoy","age":81}

As you can see, creating a JSON string with Gson is pretty easy, at least for POJO objects.