这是一个示例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
那么这里有什么问题?
答案 0 :(得分:4)
哦,这是因为Map
没有没有参数的构造函数,我可以切换到scala.collection.immutable.HashMap
然后错误没有出现,但map
没有值,它完全是空的。只有HashMap
serialVerionUID
,不再有字段。