Skip to content

Java convert to a list of objects from JSON

I am using Java 7. I also use com.fasterxml.jackson.databind.objectmapper to convert json to a Java object.

When I initially convert the the Java object to JSON, I do the following:

List<QuoteDTO> selectedQuoteDTOs = ...
String jsonSelectedQuoteDTOs = mapper.writeValueAsString(selectedQuoteDTOs);

When I convert the JSON back to a JAVA object I do the following:

List<QuoteDTO> selectedQuoteDTOs = mapper.readValue(jsonSelectedQuoteDTOs, List.class);

However the selectedQuoteDTOs are not of type QuoteDTO, but of rather of LinkedHashMap.

Resulting in me getting the following error:

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to

when I do this:

for (QuoteDTO selectedQuoteDTO : selectedQuoteDTOs) {


When converting the JSON to JAVA, how do I convert the object to a List<QuoteDTO>, instead of a List<LinkedHashMap>?

The LinkedHashMap keys are the name of the QuoteDTO member variables.


Try this. This should do the work

ObjectMapper mapper = new ObjectMapper();
List<QuoteDTO> selectedQuoteDTOs = mapper.readValue(jsonSelectedQuoteDTOs, new TypeReference<List<QuoteDTO>>(){});