Java ModelMapper将数组属性(get(0))展平为字符串?

Java ModelMapper将数组属性(get(0))展平为字符串?,java,modelmapper,Java,Modelmapper,Src对象有一个属性: private List<Pojo> goals; 我想映射Src.goals.get(0.getName()->Dest.goal。目标将始终包含一项,但它必须作为列表拉入,因为它来自Neo4j 我试着做: userTypeMap.addMappings(mapper -> { mapper.map(src -> src.getGoals().get(0).getName(), UserDto::setGoal);

Src对象有一个属性:

private List<Pojo> goals;
我想映射Src.goals.get(0.getName()->Dest.goal。目标将始终包含一项,但它必须作为列表拉入,因为它来自Neo4j

我试着做:

    userTypeMap.addMappings(mapper -> {
        mapper.map(src -> src.getGoals().get(0).getName(), UserDto::setGoal);
    });
但是modelmapper不喜欢这个参数。然后我试着:

    userTypeMap.addMappings(mapper -> {
        mapper.map(src -> src.getGoals(), UserDto::setGoal);
    });
这给了我:

"goal": "[org.xxx.models.Goal@5e0b5bd8]",

然后我尝试为List->String添加一个转换器,但没有调用它。如果我为整个pojo添加一个转换器到dto,那么我必须映射整个pojo,我不想这样做,我只想覆盖这一个属性。

您可以将
列表
访问包装在
转换器
中,并在
属性映射
中使用它,如下所示:

ModelMapper mm = new ModelMapper();
Converter<List<Pojo>, String> goalsToName = 
    ctx -> ctx.getSource() == null ? null : ctx.getSource().get(0).getName();
PropertyMap<Src, Dest> propertyMap = new PropertyMap<>() {
    @Override
    protected void configure() {
        using(goalsToName).map(source.getGoals()).setGoal(null);
    }
};
mm.addMappings(propertyMap);
ModelMapper mm=newmodelmapper();
转换器目标音调=
ctx->ctx.getSource()==null?null:ctx.getSource().get(0.getName();
PropertyMap PropertyMap=新的PropertyMap(){
@凌驾
受保护的void configure(){
使用(goalsToName).map(source.getGoals()).setGoal(null);
}
};
mm.addMappings(propertyMap);

我不太清楚您试图通过以下方式避免什么:

如果我为整个pojo添加一个转换器到dto,那么我必须映射整个pojo,我不想这样做,我只想覆盖这个属性

如果需要映射整个“pojo”或只映射一个字段,请创建一个转换器,如:

Converter<HasListOfPojos, HasOnePojo> x = new Converter<>() {
    ModelMapper mm2 = new ModelMapper();
    @Override
    public HasOnePojo convert(MappingContext<HasListOfPojos, HasOnePojo> context) {
        // do not create a new mm2 and do this mapping if no need for other
        // fields, just create a new "hop"
        HasOnePojo hop = mm2.map(context.getSource(), HasOnePojo.class);
        // here goes the get(0) mapping
        hop.setGoal(context.getSource().getGoals().get(0));
        return hop;
    }
};
Converter x=新转换器(){
ModelMapper mm2=新的ModelMapper();
@凌驾
公共HasOnePojo转换(映射上下文){
//不要创建新的mm2,如果不需要其他mm2,请进行此映射
//字段,只需创建一个新的“跃点”
HasOnePojo hop=mm2.map(context.getSource(),HasOnePojo.class);
//下面是get(0)映射
setGoal(context.getSource().getGoals().get(0));
返回跳;
}
};

不错!工作得很有魅力。谢谢
Converter<HasListOfPojos, HasOnePojo> x = new Converter<>() {
    ModelMapper mm2 = new ModelMapper();
    @Override
    public HasOnePojo convert(MappingContext<HasListOfPojos, HasOnePojo> context) {
        // do not create a new mm2 and do this mapping if no need for other
        // fields, just create a new "hop"
        HasOnePojo hop = mm2.map(context.getSource(), HasOnePojo.class);
        // here goes the get(0) mapping
        hop.setGoal(context.getSource().getGoals().get(0));
        return hop;
    }
};