我有一个这样的方法:
public List<CustomerDTO> getAllCustomers() {
Iterable<Customer> customer = customerRepository.findAll();
ObjectMapper mapper = new ObjectMapper();
return (List<CustomerDTO>) mapper.convertValue(customer, CustomerDTO.class);
}
当我尝试转换
List
值时,我收到以下消息
com.fasterxml.jackson.databind.JsonMappingException:无法从 START_ARRAY 令牌中反序列化 com.finman.customer.CustomerDTO 的实例
mapper.convertValue(customer, CustomerDTO.class)
这尝试创建单个
CustomerDTO
,而不是它们的列表。
也许这会有所帮助:
mapper.readValues(customer, CustomerDTO.class).readAll()
你可以这样做:
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);
Java 8 方式:
ObjectMapper mapper = new ObjectMapper();
List<Customer> customerList = customerRepository.findAll();
return customerList.stream().map(o -> mapper.convertValue(o, CustomerDto.class)).collect(Collectors.toList());