VijayaKumar Thangavel
VijayaKumar Thangavel

Reputation: 514

How to convert List<Entity> to List<DTO> Objects using object mapper?

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

Answers (3)

App Work
App Work

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

Kousha
Kousha

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

Joe C
Joe C

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

Related Questions