Serialising Scala literal identifiers using Gson

1 minute read Published: 2014-03-24

When converting some code using Gson to Scala, I looked at all those @SerializedName attributes and thought it should be possible to get rid of them.

Scala has a "literal identifier" feature, that enables you to use arbitrary strings as identifiers. So instead of:

@SerializedName("max-length")
val maxLength

I would like to save some boilerplate and do:

val `max-length`

The benefit is obviously fewer lines of code.

Scala needs to be compatible with any restrictions the VM imposes on field names, so this identifier will be encoded as "max$minuslength". This means that Gson will not actually (de)serialise this field as "max-length" as I wanted.

The solution is easy though. When building the Gson object, simply add a FieldNamingStrategy that decodes these mangled names:

val newGson = new GsonBuilder

newGson.setFieldNamingStrategy(new FieldNamingStrategy {
  def translateName(f: Field): String =
    scala.reflect.runtime.universe.newTermName(f.getName).decoded
})