You can use Java converters in a type adapter, but it's a bit finicky:
case class GsonListAdapter() extends JsonSerializer[List[_]] with JsonDeserializer[List[_]] {
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl
import scala.collection.JavaConverters._
@throws(classOf[JsonParseException])
def deserialize(jsonElement: JsonElement, t: Type, jdc: JsonDeserializationContext): List[_] = {
val p = scalaListTypeToJava(t.asInstanceOf[ParameterizedType]) // Safe casting because List is a ParameterizedType.
val javaList: java.util.List[_ <: Any] = jdc.deserialize(jsonElement, p)
javaList.asScala.toList
}
override def serialize(obj: List[_], t: Type, jdc: JsonSerializationContext): JsonElement = {
val p = scalaListTypeToJava(t.asInstanceOf[ParameterizedType]) // Safe casting because List is a ParameterizedType.
jdc.serialize(obj.asInstanceOf[List[Any]].asJava, p)
}
private def scalaListTypeToJava(t: ParameterizedType): ParameterizedType = {
ParameterizedTypeImpl.make(classOf[java.util.List[_]], t.getActualTypeArguments, null)
}
}
val gson = new GsonBuilder().registerTypeHierarchyAdapter(classOf[List[_]], new GsonListAdapter()).create()
val l1 = List("a", "c")
val stringListType = new TypeToken[List[String]] {}.getType
val json1 = gson.toJson(l1, stringListType)
println(json1) // ["a","c"]
val newL1: List[String] = gson.fromJson(json1, stringListType)
assert(l1 === newL1)
val l2 = List(1, 3)
val intListType = new TypeToken[List[Int]] {}.getType
val json2 = gson.toJson(l2, intListType)
println(json2) // [1,3]
val newL2: List[Int] = gson.fromJson(json2, intListType)
assert(l2 === newL2)