[英]Not able to deserialize json to case class using gson
I am working in Scala programming language and want to deserialize json to case class我正在使用 Scala 编程语言并希望将 json 反序列化为大小写 class
My case class looks like this我的案例 class 看起来像这样
case class Events
(
Name: String,
Field1: Option[Seq[String]],
Field2: Option[Seq[String]],
Field3: Option[Seq[String]]
)
case class RootInterface
(
Events: Seq[Events]
)
The json looks like this json 看起来像这样
"Events": [
{
"Name": "event1",
"Field1": ["f1"]
},
{
"Name": "event2",
"Field1": ["f1","f2"]
}
]
And the code I have to do this is我必须这样做的代码是
val gson = new Gson
gson.fromJson(json, classOf[RootInterface])
when I try to do this I get the below error当我尝试这样做时,我收到以下错误
java.lang.RuntimeException: Unable to invoke no-args constructor for scala.collection.Seq<***.Events>. java.lang.RuntimeException:无法为 scala.collection.Seq<***.Events> 调用无参数构造函数。 Register an InstanceCreator with Gson for this type may fix this problem.向 Gson 注册一个 InstanceCreator 可以解决这个问题。
Ho can I fix this?我可以解决这个问题吗?
You won't be able to us Java libraries expecting Java Beans with a standard case classes您将无法使用 Java 库来期待 Java 具有标准案例类的 Bean
var
s)你只有二传手(你没有使用var
s)@BeanProperty
)并且访问器不使用 Bean 语法(您必须使用@BeanProperty
)So you would have to use something like:所以你必须使用类似的东西:
case class Events(
@BeanProperty var name: String,
@BeanProperty var field1: Option[Seq[String]],
@BeanProperty var field2: Option[Seq[String]],
@BeanProperty var field3: Option[Seq[String]]
) {
def this() = this("", None, None, None)
}
but this means that library uses runtime reflection, which throws type safety under the bus.但这意味着库使用运行时反射,这会在总线下抛出类型安全。 Personally, I see no reason to use Java JSON libraries provided you have a choice, because I have a compile time reflection in Scala libraries.就个人而言,我认为没有理由使用 Java JSON 库,只要您有选择,因为我在 Scala 库中有编译时反射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.