0

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 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.