如何使用对象映射器将List<Entity>转换为List<DTO>对象?

问题描述 投票:0回答:3

我有一个这样的方法:

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 的实例

java jackson objectmapper
3个回答
1
投票
mapper.convertValue(customer, CustomerDTO.class)

这尝试创建单个

CustomerDTO
,而不是它们的列表。

也许这会有所帮助:

mapper.readValues(customer, CustomerDTO.class).readAll()

0
投票

你可以这样做:

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);

0
投票

Java 8 方式:

ObjectMapper mapper = new ObjectMapper();
    List<Customer> customerList = customerRepository.findAll();
    return customerList.stream().map(o -> mapper.convertValue(o, CustomerDto.class)).collect(Collectors.toList());
© www.soinside.com 2019 - 2024. All rights reserved.