3

Here is a sample Scala object in which I want to deserialize a JSON String to a Map of String -> String. I use GSON 2.2.2 and Scala 2.10.

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

object MyTest {
  def main(args: Array[String]) {
    val gson = new Gson
    val jsonString = "{\"test1\": \"value-test1\",\"test2\":\"value-test2\"}"
    val mapType = new TypeToken[Map[String, String]] {}.getType
    val map = gson.fromJson(jsonString, mapType).asInstanceOf[Map[String, String]]
  }
}

And that is the stack trace thrown in the line of val map = ...:

Exception in thread "main" java.lang.RuntimeException: Unable to invoke no-args 
    constructor for 
    scala.collection.immutable.Map<java.lang.String, java.lang.String>.

Register an InstanceCreator with Gson for this type may fix this problem.
at com.google.gson.internal.ConstructorConstructor$8.construct(ConstructorConstructor.java:167)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:162)
at com.google.gson.Gson.fromJson(Gson.java:795)
at com.google.gson.Gson.fromJson(Gson.java:761)
at com.google.gson.Gson.fromJson(Gson.java:710)
at MyTest$.main(MyTest.scala:9)
at MyTest.main(MyTest.scala)

Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.google.gson.internal.UnsafeAllocator$1.newInstance(UnsafeAllocator.java:48)
at com.google.gson.internal.ConstructorConstructor$8.construct(ConstructorConstructor.java:164)
... 6 more

Caused by: java.lang.InstantiationException: scala.collection.immutable.Map
at sun.misc.Unsafe.allocateInstance(Native Method)
... 12 more

So what's wrong here?

Tim
  • 13,228
  • 36
  • 108
  • 159

1 Answers1

5

Oh, it is because Map does not have a constructor with no arguments, I can switch to scala.collection.immutable.HashMap then the error does not appear, but the map does not have the values, it is completely empty. It is only a HashMap with serialVerionUID, no more fields.

Tim
  • 13,228
  • 36
  • 108
  • 159