GSON with Scala: Scala scala.collection.mutable.HashMap vs. java.util.HashMap

gson, json, scala

Solution

I don't know GSON, but it's a Java library, so I don't see a reason why it would understand Scala types.

I guess you could deserialize your JSON into a Java map and wrap it into Scala map using conversions provided by `scala.collections.JavaConverters` or `scala.collection.JavaConversions`. For example:

import java.{util => ju}
import scala.collection.JavaConverters._

val gson = new Gson
val jsonString = "{\"test1\":\"value-test1\",\"test2\":\"value-test2\"}"
val mapType = new TypeToken[ju.HashMap[String, String]] {}.getType
val map = gson.fromJson[ju.Map[String, String]](jsonString, mapType).asScala

Problem

I am using Scala 2.10 with the latest version of GSON. I want to deserialize a JSON String into a `scala.collection.mutable.HashMap`. But the value of `map` is empty, only a `HashMap`with a `serialVersionUID`, no more fields. ``` import com.google.gson.Gson import com.google.gson.reflect.TypeToken import scala.collection.mutable.HashMap object MyTest { def main(args: Array[String]) { val gson = new Gson val jsonString = "{\"test1\":\"value-test1\",\"test2\":\"value-test2\"}" val mapType = new TypeToken[HashMap[String, String]] {}.getType val map = gson.fromJson(jsonString, mapType).asInstanceOf[HashMap[String, String]] } } ``` Trying it with a `java.util.HashMap` instead of `scala.collection.mutable.HashMap`, it works. I have a `map` with the entries. But why doesn't it work with the Scala HashMap?

Original source