【问题标题】:How to map a nested list using ModelMapper如何使用 ModelMapper 映射嵌套列表
【发布时间】:2021-12-08 11:39:15
【问题描述】:

我遇到了一个问题,我正在使用 ModelMapper 来映射对象,但我发现自己无法使用自定义映射来解决这个问题。

这是我的源模型:

public class UserSource {
    
    private List<IdentitySource> identities;
    
}

public class IdentitySource {
    
    private String firstName;
    private String lastName;
    
}

这是我的目标模型:

public class UserDestination {
    
    private List<NestedIdentityDestination> nestedIdentities;
    
}

public class NestedIdentityDestination {
    
    private IdentityDestination identity;
    
}

public class IdentityDestination {

    private String firstName;
    private String lastName;
    
}

请问有人知道如何使用 ModelMapper 来实现吗?

【问题讨论】:

  • Identity = IdentitySource?
  • 对,我编辑了我的问题和答案,感谢您指出这一点。

标签: java modelmapper


【解决方案1】:

在做了更多的研究和实验之后,我想通了。我需要混合使用转换器和类型映射。

这是我的解决方案:

Converter<List<IdentitySource>, List<NestedIdentityDestination>> convertIdentities = new AbstractConverter<>() {
    protected List<NestedIdentityDestination> convert(List<IdentitySource> source) {
        return source.stream().map(identity -> {
            NestedIdentityDestination nestedIdentity = new NestedIdentityDestination();
            nestedIdentity.setIdentity(modelMapper.map(identity, IdentityDestination.class));
            return nestedIdentity;
        }).collect(Collectors.toList());
    }
};

modelMapper.typeMap(UserSource.class, UserDestination.class)
        .addMappings(mapper -> mapper.using(convertIdentities)
                .map(UserSource::getIdentities, UserDestination::setNestedIdentities));

希望这可以帮助其他面临同样问题的人。

【讨论】:

    猜你喜欢
    • 2019-10-27
    • 2020-04-06
    • 2011-11-22
    • 1970-01-01
    • 2017-05-25
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    相关资源
    最近更新 更多