Mapstruct:将“脏”字符串字段映射为double

问题描述 投票:1回答:2

鉴于:

String SourcePojo.area = "120,5 sqm"
double TargetPojo.area = 120.5

我可以通过以下方式将“脏”字符串转换为数字:

double extractDoubleFromString(String string) throws ParseException{
    NumberFormat format = NumberFormat.getInstance(Locale.GERMAN);
    return format.parse(string).doubleValue();
}

我试过的

使用Mapstruct我写了这个Mapper:

@Mapper
public interface MyMapper {

    MyMapper INSTANCE = Mappers.getMapper(MyMapper.class);


    @Mapping(source="space", target="space", qualifiedByName="StringToDouble")
    TargetPojo mapSourceToTarget(TargetPojo aAED);

    @Named("StringToDouble")
    default double extractDoubleFromString(String string) throws ParseException{
        NumberFormat format = NumberFormat.getInstance(Locale.GERMAN);
        return format.parse(string).doubleValue();
    }
}

在生成的MapperImpl中我找到了这段代码:

    if ( aAED.getSpace() != null ) {
        targetPojo.space( Double.parseDouble( aAED.getSpace() ) );
    }

看起来似乎根本没有使用命名方法。我仍然得到与添加之前相同的错误。

java mapping number-formatting mapstruct
2个回答
0
投票

我刚试过你的映射器

@Mapper
public interface MyMapper {

    MyMapper INSTANCE = Mappers.getMapper(MyMapper.class);

    @Mapping(source = "space", target = "space", qualifiedByName = "StringToDouble")
    TargetPojo mapSourceToTarget(SourcePojo aAED);

    @Named("StringToDouble")
    default double extractDoubleFromString(String string) throws ParseException {
        NumberFormat format = NumberFormat.getInstance(Locale.GERMAN);
        return format.parse(string).doubleValue();
    }
}

这会产生:

try {
    targetPojo.setSpace( extractDoubleFromString( aAED.getSpace() ) );
}
catch ( ParseException e ) {
    throw new RuntimeException( e );
}

它可能不适合你的一个原因是你不使用org.mapstruct.Named,而是使用另一个包中的@Named


0
投票

代码完全正常,应该可以工作。它没有的原因是,MapStruct不是由普通的Eclipse Builder调用的,而是通过Maven构建过程调用的。 (至少我的设置是这样)

完成maven clean安装后,新的映射器已创建,一切运行良好。

© www.soinside.com 2019 - 2024. All rights reserved.