Reputation: 595
I am sending a request to the controller https://pastebin.com/d4SHZuZh. JSON deserialize using Builder from this class. @JsonDeserialize(builder = ContributionNewRequest.Builder.class)
The elements of the collection are ? extends MovieInfoDTO
objects inheriting from MovieInfoDTO
.
when getting items from e.g. list elementsToAdd
contribution.getElementsToAdd()
.forEach(boxOffice -> {
...
});
it turns out that the boxOffice
element is a java.util.LinkedHashMap
object.
I found a mention on the internet on the Internet http://www.baeldung.com/jackson-collection-array that JSON default sets the elements of the collection as LinkedHashMap
.
What do I need to do to make the objects of the correct type?
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.jonki.popcorn.common.dto.movie.BoxOffice
at java.util.ArrayList.forEach(ArrayList.java:1257) ~[na:1.8.0_171]
Upvotes: 2
Views: 1561
Reputation: 509
You should custom your deserialize builder.
Try something like this
public class CustomDeserializer extends StdDeserializer<List<? extends MovieInfoDTO>> {
protected CustomDeserializer(Class<?> vc) {
super(vc);
}
@Override
public List<? extends MovieInfoDTO> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
String json = jsonParser.getText();
TypeReference type = new TypeReference<List<? extends MovieInfoDTO>>() {};
return objectMapper.readValue(json, type);
}
}
Finally add @JsonDeserialize(using = CustomDeserializer.class)
before your elementsToAdd
property
Hope this will help you a bit.
Upvotes: 3
Reputation: 15878
Try to convert it using following code.
public <T> List<T> jsonToObjectList(String json, Class<T> tClass) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
List<T> ts = objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, tClass));
return ts;
}
Upvotes: 0