Home > OS >  How map List into DTO
How map List into DTO

Time:10-17

I have this problem, this is my DTO:

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

Here my other DTO:

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

But I need map OrderEmbeddedListJsonDTO propertie since OrderDTO for example:

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

This is the class of orderDTOMapped:

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();
        }
    };

And order is a entity:

public class Order implements java.io.Serializable {

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

How can do this? Could you help me please?

CodePudding user response:

You can iterate over the OrderDTO#embedded items mapping each items to a new instances copying / replacing whatever data you need:

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;
}
  • Related