Reputation: 514
I have a method like this:
public List<CustomerDTO> getAllCustomers() {
Iterable<Customer> customer = customerRepository.findAll();
ObjectMapper mapper = new ObjectMapper();
return (List<CustomerDTO>) mapper.convertValue(customer, CustomerDTO.class);
}
when i try to convert List
values i am getting below message
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.finman.customer.CustomerDTO out of START_ARRAY token
Upvotes: 2
Views: 12032
Reputation: 22039
Java 8 way:
ObjectMapper mapper = new ObjectMapper();
List<Customer> customerList = customerRepository.findAll();
return customerList.stream().map(o -> mapper.convertValue(o, CustomerDto.class)).collect(Collectors.toList());
Upvotes: 0
Reputation: 36299
You can do something like:
static <T> List<T> typeCastList(final Iterable<?> fromList,
final Class<T> instanceClass) {
final List<T> list = new ArrayList<>();
final ObjectMapper mapper = new ObjectMapper();
for (final Object item : fromList) {
final T entry = item instanceof List<?> ? instanceClass.cast(item) : mapper.convertValue(item, instanceClass);
list.add(entry);
}
return list;
}
// And the usage is
final List<DTO> castedList = typeCastList(entityList, DTO.class);
Upvotes: 0
Reputation: 15714
mapper.convertValue(customer, CustomerDTO.class)
This attempts to create a single CustomerDTO
, not a list of them.
Perhaps this will help:
mapper.readValues(customer, CustomerDTO.class).readAll()
Upvotes: 1