推土机从具有地图的对象映射到具有属性的Pojo

时间:2015-01-02 12:36:05

标签: java mapping dozer

我正在尝试使用Dozer从源到目的地进行单向映射。

public class Source {
    Map<String, String> values;
    public Source() {
    }
    public Source(Map<String, String> values) {
        this.values = values;
    }
    public Map<String, String> getValues() {
        return values;
    }
    public void setValues(Map<String, String> values) {
        this.values = values;
    }
}

public class Destination {
    private String lastname;
    private String firstname;
    public Destination() {
    }
    public String getLastname() {
        return lastname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public String getFirstname() {
        return firstname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
}

这是我的测试类:

public class DozerMapperTest {
    private DozerMapper mapper = new DozerMapper();
    @Test
    public void testName() throws Exception {
        String firstname = "Tom";
        String lastname = "Hanks";
        Map<String, String> input = new HashMap<>();
        input.put("firstname", firstname);
        input.put("lastname", lastname);
        Destination result = mapper.map(new Source(input));
        Assert.assertNotNull(result);
        Assert.assertEquals(firstname, result.getFirstname());
        Assert.assertEquals(lastname, result.getLastname());
    }
}

我的映射类看起来像这样:

public class DozerMapper {
    public DozerMapper() {
        initMapper();
    }
    private DozerBeanMapper mapper;
    public Destination map(final Source input) {
        return mapper.map(input, Destination.class);
    }
    void initMapper() {
        BeanMappingBuilder builder = new BeanMappingBuilder() {
            @Override
            protected void configure() {
                mapping(Source.class, Destination.class, TypeMappingOptions.oneWay())
                        .fields(new FieldDefinition("values.lastname"), "lastname")
                        .fields(new FieldDefinition("values.firstname"), "firstname");
            }
        };
        mapper = new DozerBeanMapper();
        mapper.addMapping(builder);
    }
}

但他的一切都没有用:-( 我也试过这个映射:

.fields(new FieldDefinition("values").mapKey("lastname"), "lastname")
.fields(new FieldDefinition("values").mapKey("firstname"), "firstname");

我用谷歌搜索,看着dokumentation,没有。 有人可以帮我或给我一些提示吗?

1 个答案:

答案 0 :(得分:0)

在我刚才研究之前,我自己并不认为这是可能的,所以感谢你的问题!

正确的做法是:

.fields("values", "firstname")
.fields("values", "lastname");

这里的关键点是变量&#34; firstname&#34;和&#34;姓氏&#34;在Destination类中必须与Source类中的键相同。地图。否则这不会起作用。