首页 > 解决方案 > 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 的空值

标签: javaspring-bootmapstructobject-object-mapping

解决方案


据我了解,您需要将列表映射到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);

}

如果您需要进行计算并拥有来自不同级别的对象,并且需要进行一些分组和/或聚合,我建议您编写自己的逻辑。


推荐阅读