java - MapStruct - 嵌套映射
问题描述
我需要将来自第三方 API 的响应映射到另一个响应结构。我正在为此使用 Mapstruct。
第三方 API 类:
public class TPResponse {
protected UserListsType userLists;
protected ProductOffers offers;
//getters and setters
}
public class UserListsType {
protected UserTypes userTypes;
...............
}
public class UserTypes{
protected List<User> userType;
}
public class User{
protected String userID;
}
public class ProductOffers {
protected List<OffersType> OffersType;
}
public class OffersType{
protected PriceType totalPrice;
}
我们的 API 类:
public class ActualResponse {
private List<Customer> user = new ArrayList<Customer>();
//getters and setters
}
public class Customer{
private String customerId;
private String pdtPrice;
private OfferPrice offerPrice;
}
public class OfferPrice{
private String offerId;
}
我想使用 MapStruct 映射这些元素。
1) customerId <Map with> UserTypes->User->userID
2) pdtPrice <Map with> offers -> OffersType -> totalPrice
3) offerId <Map with> sum of (offers -> OffersType -> totalPrice)
我尝试使用 MapStruct 编写 Mapper 类,例如:
@Mapper(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
public interface UserResponseMapper {
UserResponseMapper RESPONSE_MAPPER = Mappers.getMapper(UserResponseMapper.class);
@Mappings({
@Mapping(target="customer.customerId", source="userTypes.userType.userId")
})
ActualResponse mapUser(UserListsType userListType);
}
目前它显示像“未知属性“customer.customerId”和“userTypes.userType.userId”这样的错误。任何人都可以帮我使用 Mapstruct 映射所有这些元素吗?
问题 2:我们如何映射以下内容?1) customerId UserTypes->User->userID 2) pdtPrice offer -> OffersType -> totalPrice 3) offerId sum of (offers -> OffersType -> totalPrice)
我试过了
@Mapping(target = "customerId", source = "userId")
@Mapping(target = "pdtPrice", source = "totalPrice")
User mapUser(UserListsType userListType, OffersType offersType );
我得到 customerId 和 pdtPrice 的空值
解决方案
据我了解,您需要将列表映射到ActualResponse
和中UserTypeListType
。
当您提供某些对象之间的映射时,MapStruct 可以自动生成其集合之间的映射。因此,在您的情况下,您需要执行以下操作:
@Mapper(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
public interface UserResponseMapper {
UserResponseMapper RESPONSE_MAPPER = Mappers.getMapper(UserResponseMapper.class);
@Mappings({
@Mapping(target="user", source="userType")
})
ActualResponse mapUser(UserTypeListType userListType);
@Mapping(target = "customerId", source = "userId")
User mapUser(UserType userType);
}
如果您需要进行计算并拥有来自不同级别的对象,并且需要进行一些分组和/或聚合,我建议您编写自己的逻辑。
推荐阅读
- c# - 正确使用 ref 关键字
- google-app-engine - Google App Engine - PM2 - 启动程序失败:启动后未能检测到应用程序:ForAppStart():
- ios - 获取在 ARKit 中检测到的平面的宽度和高度
- sql - Levenshtein 距离的模糊连接
- django - Django:在创建用户之前验证电子邮件
- delphi - Delphi 风格的速度按钮在 MacOS 上失去透明度
- sorting - 使用插入排序对字符串进行两次排序
- python - 如何在 discord.py 欢迎消息中使用 ctx?
- java - 使用 open cv 获取数独网格线
- authentication - 在 Cognito 中具有授权的服务器到服务器通信?