Error while Parsing json into scala case class

731 views Asked by At

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?

2

There are 2 answers

0
Gregor Raýman On BEST ANSWER

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);
0
Dan Gravell On

Because of type erasure, the parameterized type of the List is lost at runtime.

Instead, use the Scala module for Jackson and you can simply do:

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

So long as the Scala module has been registered - this means a Scala List will be created.