GSon fromJson在Scala中的Arrays失败

时间:2016-07-28 16:06:36

标签: scala gson

我正在使用Scala的Gson库。我的JSON看起来像

{"response":{"id":"xyz","userName":"foo","firstName":"foo","lastName":"bar","groups":["A", "B", "C"]}, "count":1}

要解析这个,我写了以下代码

case class MyAdmin(id: String, userName: String, firstName: String, lastName: String, groups: List[String])
case class MyResponse(response: MyAdmin, count: Int)

我的解析代码看起来像

val respScala = gson.fromJson(responseString, classOf[MyResponse])

但是我收到了错误

Exception in thread "main" java.lang.RuntimeException: Failed to invoke public scala.collection.immutable.List() with no args
    at com.google.gson.internal.ConstructorConstructor$3.construct(ConstructorConstructor.java:111)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:210)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:129)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:220)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:129)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:220)
    at com.google.gson.Gson.fromJson(Gson.java:887)
    at com.google.gson.Gson.fromJson(Gson.java:852)
    at com.google.gson.Gson.fromJson(Gson.java:801)
    at com.google.gson.Gson.fromJson(Gson.java:773)
    at com.foo.FlareCommandLine$.delayedEndpoint$com$foo$FlareCommandLine$1(FlareCommandLine.scala:28)
    at com.researchnow.FlareCommandLine$delayedInit$body.apply(FlareCommandLine.scala:17)
    at scala.Function0$class.apply$mcV$sp(Function0.scala:34)
    at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
    at scala.App$$anonfun$main$1.apply(App.scala:76)
    at scala.App$$anonfun$main$1.apply(App.scala:76)
    at scala.collection.immutable.List.foreach(List.scala:381)

1 个答案:

答案 0 :(得分:0)

做了一些研究,发现Gson不能很好地处理scala集合。我用Json4s替换了Gson ...现在一切正常,我能够轻松地反序列化我的json。

有人必须告诉Alvin Alexander先生更新他的博客。他正在使用许多旧工具和代码,但谷歌总会指向他的博客。