我需要将来自第三方API的响应映射到另一个响应结构。我使用Mapstruct来实现这一点。
ThirdParty应用编程接口类:
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(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用户类型->用户->用户of 2) pdtPrice offers -> 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的空值
发布于 2020-07-23 14:22:52
据我所知,您需要映射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);
}如果您需要进行计算,并且具有来自不同级别的对象,并且需要进行一些分组和/或聚合,我建议您编写自己的逻辑。
https://stackoverflow.com/questions/63040246
复制相似问题