如何将列表映射到 DTO

How map List into DTO

我有这个问题,这是我的 DTO:

public class OrderDTO {
    private Long id;
    @JsonProperty("_embedded")
    private OrderEmbeddedListJsonDTO embedded;
}

这是我的另一个 DTO:

public class OrderEmbeddedListJsonDTO {
    private List<Order> order;
}

但是我需要映射 OrderEmbeddedListJsonDTO 属性,因为 OrderDTO 例如:

orderDTOMapped.setEmbedded(order.getEmbedded(HERE NEED: setStartAddress("new value")));

这是 orderDTOMapped 的 class:

public OrderWithAddressDTO orderToOrderDTO(OrderDTO order) throws OrderGetException {
        try {
                OrderWithAddressDTO orderDTOMapped = new OrderWithAddressDTO();
                orderDTOMapped.setId(order.getId());
                orderDTOMapped.setEmbedded(order.getEmbedded());
            return orderDTOMapped;
        }  catch (Exception e) {
            throw new OrderGetException();
        }
    };

订单是一个实体:

public class Order implements java.io.Serializable {

    private Long id;
    private Double latitude;
    private Double longitude;
    @JsonProperty("_embedded")
    private OrderEmbeddedListJsonDTO embedded;
}

如何做到这一点?你能帮帮我吗?

已更新:

我可以用这段代码修复它:

List<Order> shippableOrders = order.getEmbedded()
                        .getOrder()
                        .stream()
                        .map(this::mapOrderToShippableOrder)
                        .collect(Collectors.toList());
                OrderEmbeddedListJsonDTO ordersList = new OrderEmbeddedListJsonDTO();
                ordersList.setOrder(shippableOrders);
                orderDTOMapped.setEmbedded(ordersList);
                return orderDTOMapped;

感谢您的帮助,谢谢
tmarwen

您可以遍历 OrderDTO#embedded 个项目,将每个项目映射到一个新实例,复制/替换您需要的任何数据:

public OrderWithAddressDTO orderToOrderDTO(OrderDTO order) throws OrderGetException {
    try {
        OrderWithAddressDTO orderDTOMapped = new OrderWithAddressDTO();
        orderDTOMapped.setId(order.getId());
        List<Order> shippableOrders = order.getEmbedded()
                .getOrder()
                .stream()
                .map(this::mapOrderToShippableOrder)
                 .collect(Collectors.toList());
        OrderEmbeddedListJsonDTO ordersList = new OrderEmbeddedListJsonDTO();
        ordersList.setEmbedded(ordersList);
        return orderDTOMapped;
    }  catch (Exception e) {
        throw new OrderGetException();
    }
};

private Order mapOrderToShippableOrder(Order order) {
    Order result = new Order();
    // map fields from `order` to `result` order including `new-address`
    return result;
}