3

这是一个示例 Scala 对象,我想在其中将 JSON 字符串反序列化为Map of String -> String. 我使用 GSON 2.2.2 和 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]]
  }
}

这就是在以下行中抛出的堆栈跟踪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

那么这里有什么问题呢?

4

1 回答 1

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.

于 2013-03-09T14:16:36.590 回答