My Favorite Little Annotation — Nov. 24, 2011

Jerkson is Coda Hale's small JSON library for Scala. It's a wrapper around Jackson, a fast Java JSON library with a nice API. Jerkson has been around for a little over a year, and we use it everywhere at Simple.

A recent commit added a little annotation, JsonSnakeCase, to Jerkson. This helps you do one thing: you can define a field name as Javaland-standard camelCase, yet still serialize and deserialize that field name with snake_casing.

Start with the usual case class and add the annotation —

    @JsonSnakeCase
    case class Person(firstName: String, lastName: String)
    

and use idiomatic Scala method names —

    val dax = Person("Jadzia", "Dax")
    dax.firstName
    

all the while, still generating standard-ish JSON names —

    {"first_name": "Jadzia", "last_name": "Dax"}
    

The implementation is quite simple and it just works. Even better, the same functionality is now available in Coda's rapidly-developing Dropwizard library, for Java and Scala.

⇐ ted.io