简体   繁体   English

将 json 解析为 scala 案例类时出错

[英]Error while Parsing json into scala case class

In my spring(mvc) web application, I am using org.codehaus.jackson.map.ObjectMapper in my scala code to map my json to scala objects using case classes.在我的 spring(mvc) Web 应用程序中,我在我的 scala 代码中使用org.codehaus.jackson.map.ObjectMapper使用案例类将我的 json 映射到 scala 对象。 My Json String is an array of json objects objects.我的 Json String 是一个 json 对象数组。 so I am using:所以我正在使用:

val user = mapper.readValue(myJson, classOf[List[MyClass]])

This line throws an error:此行会引发错误:

Exception in thread "main" org.codehaus.jackson.map.JsonMappingException: Can not construct instance of scala.collection.immutable.List, problem: abstract types can only be instantiated with additional type inform线程“主”org.codehaus.jackson.map.JsonMappingException 中的异常:无法构造 scala.collection.immutable.List 的实例,问题:抽象类型只能通过附加类型通知来实例化

Am I using it right or is there any other way?我使用正确还是有其他方法?

The problem is the Java type erasure.问题是Java类型擦除。 classOf[List[MyClass]] at runtime is the same as classOf[List[_]] .运行时的classOf[List[MyClass]]classOf[List[_]]相同。 That is why Jackson cannot know, which types of the elements to create.这就是为什么杰克逊不知道要创建哪些类型的元素。

Luckily Jackson does support parsing with the JavaType , which describes the types themselves.幸运的是,Jackson 确实支持使用JavaType进行解析,它描述了类型本身。

Here a simple sample in Java:这是Java中的一个简单示例:

JavaType type = mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class);
mapper.readValue(myJson, type);

Because of type erasure, the parameterized type of the List is lost at runtime.由于类型擦除,List 的参数化类型在运行时丢失。

Instead, use the Scala module for Jackson and you can simply do:相反,使用Jackson 的 Scala 模块,您可以简单地执行以下操作:

mapper.readValue(myJson, new TypeReference[List[MyClass]])

So long as the Scala module has been registered - this means a Scala List will be created.只要 Scala 模块已注册 - 这意味着将创建一个 Scala 列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM