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. My Json String is an array of json objects objects. 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

Am I using it right or is there any other way?


The problem is the Java type erasure. classOf[List[MyClass]] at runtime is the same as 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.

Here a simple sample in Java:

JavaType type = mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class);
mapper.readValue(myJson, type);
链接地址: http://www.djcxy.com/p/68278.html

上一篇: 建议将PHP会话存储在MemCache中吗?

下一篇: 将json解析为scala case类时出错