Home > Mobile >  class java.util.LinkedHashMap cannot be cast to class [...]
class java.util.LinkedHashMap cannot be cast to class [...]

Time:12-10

I'm making a GET request to a WooCommerce API to fetch orders and my idea is to grab some data from the response and insert it into a local database. I tested the request and everything works correctly. So I continued using QuickType to be able to create the classes corresponding to the response, so I have a way to save it and insert it into the database. The problem is the following, if I comment the "for" statement, there is no problem. But at the moment of using it to obtain the values of the answer and insert them to the database, this error occurs: class java.util.LinkedHashMap cannot be cast to class [name of my class]. And also: [my class] is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader. Can you help me to find a way to solve this problem? Here is the code:

@GetMapping("/ordenes")
    public List<WcOrden> getOrdenes() {

        List<WcOrden> ordenes = (List<WcOrden>) wc.getAll(EndpointBaseType.ORDERS.getValue(), params);
        for (WcOrden orden : ordenes) {
            log.debug("This is an order");
        }
        return ordenes;
    }

CodePudding user response:

I assume wc.getAll(...) is a call to an external API.

When Jackson does not have enough information about what class to deserialize to, it uses LinkedHashMap.

In your case, it knows it is a List, but not the actual type of the elements inside the list, as explained in this article.

So, to solve it, you can use the convertValue of the ObjectMapper:

ObjectMapper mapper = new ObjectMapper(); // or inject it as a dependency
List<WcOrden> pojos = mapper.convertValue(wc.getAll(...), new TypeReference<List<WcOrden>>() { });
  • Related