Gson works really well in Scala, as long as you stick to the types it's aware of - Int, String, Array, etc. Use var rather than val and make sure there's a no-args constructor:
class MyType(var title: String, var foo: Int) {
def this() = this("", 0)
}
Out of the box, Gson doesn't know about Scala types like List, nor does it know about Joda times. I'm trying to add some custom serialization handlers, as suggested in the user guide, but I hit an issue when it comes to Option. Option is a container like an array or list, but it can either contain one value, in which case it's called Some(x), or None. I tried adding a custom serializer for Option, like so:
object OptionSerializer extends JsonSerializer[Option[_]] with JsonDeserializer[Option[_]] {
def serialize(src: Option[_], typeOfT: Type, context: JsonSerializationContext) =
case Some(v) => context.serialize(v, typeOfT)
def deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext) =
case _ if json.isJsonNull => None
case _ => Some(context.deserialize(json, typeOfT))
builder.registerTypeAdapter(classOf[Option[_]], OptionSerializer)
The problem is with the typeOfT parameter. At runtime this appears to be a com.google.gson.ParameterizedTypeImpl. How do I convert that to the inner type that needs to be passed in?