0

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.

Richard
  • 8,193
  • 28
  • 107
  • 228
  • This might be a solution: https://stackoverflow.com/questions/16428817/convert-a-mapstring-string-to-a-pojo – Richard Dec 08 '20 at 13:31

1 Answers1

1

Try this. This should do the work

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