ModelMapper:将具有嵌套集合的地图对象映射到平面对象

时间:2019-12-10 14:06:07

标签: java mapper modelmapper

我有一个带有嵌套列表的类,我想使用ModelMapper将此对象映射到平面对象列表中。

public class A {
  private String str;
  private String str2;
  private List<B> blist;

  // Setters and getters
}

public class B {
  private String str3;
  private String str4;

  // Setters and getters
}

public class C {
  private String str;
  private String str2;
  private String str3;
  private String str4;

  // Setters and getters
}

我想将A类的对象转换为C类的对象列表

1 个答案:

答案 0 :(得分:0)

我认为,对于这种转换,您需要自定义Converter
因此,一个完整的非Stream解决方案是

// Create the custom Converter
final Converter<A, Collection<C>> toCList = new AbstractConverter<A, Collection<C>>() {
    @Override
    protected Collection<C> convert(final A a) {
        final Collection<B> bList = a.getBlist();
        final Collection<C> cList = new ArrayList<C>(bList.size());

        for (final B b : bList) {
            final C c = new C();
            c.setStr(a.getStr());
            c.setStr2(a.getStr2());
            c.setStr3(b.getStr3());
            c.setStr4(b.getStr4());
            cList.add(c);
        }

        return cList;
    }
};

// Set-up the example starting object
final B b = new B();
b.setStr3("Three");
b.setStr4("Four");

final A a = new A();
a.setStr("One");
a.setStr2("Two");
a.setBlist(Arrays.asList(b, b));

// Initialize the mapper with the custom converter defined above
final ModelMapper modelMapper = new ModelMapper();
modelMapper.addConverter(toCList);

// Map to the Collection using a TypeToken,  
// to avoid the non-reified generics problem
final Collection<C> result = modelMapper.map(
   a, 
   new TypeToken<Collection<C>>() {}.getType()
);

Stream的{​​{1}}版本是

convert