Skip to content
Advertisement

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 com.abc.model.QuoteDTO

when I do this:

for (QuoteDTO selectedQuoteDTO : selectedQuoteDTOs) {

Question

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.

Advertisement

Answer

Try this. This should do the work

ObjectMapper mapper = new ObjectMapper();
List<QuoteDTO> selectedQuoteDTOs = mapper.readValue(jsonSelectedQuoteDTOs, new TypeReference<List<QuoteDTO>>(){});
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement