【问题标题】:How to convert List<Entity> to List<DTO> Objects using object mapper?如何使用对象映射器将 List<Entity> 转换为 List<DTO> 对象?
【发布时间】:2017-03-12 09:30:25
【问题描述】:

我有这样的方法:

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

【问题讨论】:

  • 作为一般规则,当您发现自己在投射时,您可能没有做您认为自己正在做(或想做)的事情。
  • 你为什么要这样做?您是否意识到这包括将客户序列化为 JSON,然后将 JSON 解析为 CustomerDTO?如果两个类没有相同的结构,它会非常低效,晦涩,在运行时会失败,并且不支持重构。为什么不直接创建一个构造函数或从客户创建 CustomerDTO 的方法?

标签: java objectmapper


【解决方案1】:
mapper.convertValue(customer, CustomerDTO.class)

这会尝试创建一个 CustomerDTO,而不是它们的列表。

也许这会有所帮助:

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

【讨论】:

  • 那该用什么?如果我不使用那个 CustomerDTO,对象映射器将如何知道要转换哪个对象?
  • 抱歉错过了。我尝试了相同的方法,但收到以下警告 ObjectMapper 类型中的方法 readValues(JsonParser, ResolvedType) 不适用于参数 (Iterable, Class)
【解决方案2】:

你可以这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多