gpt4 book ai didi

java - ModelMapper - 如何从源计算值并将其设置为目标

转载 作者:行者123 更新时间:2023-12-01 19:02:39 27 4
gpt4 key购买 nike

我正在尝试使用 ModelMapper 将源映射到目标。

在我的具体情况下,在源类中有一个属性(评论列表),我必须在其中按评级求和并将该值设置为目标类。

所以我尝试使用转换器,但它不起作用。

        Converter<List<Review>, Double> sumReviewsRating = new AbstractConverter<List<Review>, Double>() {
@Override
protected Double convert(List<Review> reviews) {
if(reviews!=null){
return reviews.stream().mapToDouble(Review::getRating).sum();
//it doesn't work also with return 1.0 for example;
}else{
return 0.0;
}
}
};

modelMapper.typeMap(MySource.class, MyDestination.class).addMappings(mapper ->{
mapper.map(MySource::getCoverImageId, MyDestination::setImageUrl); //this works
mapper.using(sumReviewsRating).map(MySource::getReviews, MyDestination::setRating);
});

堆栈跟踪:

org.modelmapper.internal.ErrorsException: null
at org.modelmapper.internal.Errors.toException(Errors.java:254) ~[modelmapper-2.3.6.jar:na]
at org.modelmapper.internal.ReferenceMapExpressionImpl.map(ReferenceMapExpressionImpl.java:71) ~[modelmapper-2.3.6.jar:na]
at org.modelmapper.internal.ConfigurableConditionExpressionImpl.map(ConfigurableConditionExpressionImpl.java:65) ~[modelmapper-2.3.6.jar:na]

如果我在转换器中放置断点,它就不会进入。

我的赌注在哪里?

最佳答案

以下内容对我有用:

ModelMapper modelMapper = new ModelMapper();

Converter<List<String>, Double> sumReviewsRating = new AbstractConverter<List<String>, Double>() {
@Override
protected Double convert(List<String> reviews) {
if(reviews!=null){
return 1.0;
//it work also with return 1.0 for example;
}else{
return 0.0;
}
}
};

modelMapper.typeMap(MySource.class, MyDestination.class).addMappings(mapper ->{
mapper.using(sumReviewsRating).map(MySource::getReview, MyDestination::setRating);
});

MySource mySource = new MySource();
mySource.setReview(Arrays.asList(new String[]{"1","2"}));
MyDestination destination = modelMapper.map(mySource,MyDestination.class);

System.out.println(destination.getRating());

类(class)

@Getter @Setter
public class MyDestination {
Double rating;
}


@Getter @Setter
public class MySource {
List<String> review;
}

上面的代码成功完成了转换。

尝试添加多个这样的映射

**

typeMap.addMappings(mapper -> mapper.<String>map(Src::getA, Dest::setB))
.addMappings(mapper -> mapper.<String>skip(Dest::setB))

**

关于java - ModelMapper - 如何从源计算值并将其设置为目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59610414/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com