Reputation: 1980
I need to map a response from third party API to another response structure. I'm using Mapstruct for that.
ThirdParty API classes :
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;
}
Our API classes :
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;
}
I want to map these elements using MapStruct.
1) customerId <Map with> UserTypes->User->userID
2) pdtPrice <Map with> offers -> OffersType -> totalPrice
3) offerId <Map with> sum of (offers -> OffersType -> totalPrice)
I tried to write Mapper Class using MapStruct like :
@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);
}
Currently it shows the error like "Unknown property "customer.customerId" and "userTypes.userType.userId". Can anyone please help me to map all those elements using Mapstruct?
Question no 2 : How can we map following? 1) customerId UserTypes->User->userID 2) pdtPrice offers -> OffersType -> totalPrice 3) offerId sum of (offers -> OffersType -> totalPrice)
I tried
@Mapping(target = "customerId", source = "userId")
@Mapping(target = "pdtPrice", source = "totalPrice")
User mapUser(UserListsType userListType, OffersType offersType );
I'm getting null values for customerId and pdtPrice
Upvotes: 2
Views: 6894
Reputation: 21403
From what I can understand you need to map the lists in ActualResponse
and UserTypeListType
.
When you provide a mapping between certain objects MapStruct can automatically generate mapping between its collections. So in your case you'll need to do something like:
@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);
}
If you need to do calculations and have objects from different levels and you need to do some groupings and or aggregations I would suggest that you write your own logic.
Upvotes: 3