0

Im having some issues trying to convert a List of Object to a custom DTO. However, all the answers that i found are focused on converting Entities or POJ0s to DTO. How can i do this in either some kind of iteration, or even manyally accesing all the Object properties?

Right now i have something like this that throw some casting errors, but idk if changing datatypes would work or if i should try something else.

List<Object> ls = myDAO.getSomethingFromDB();
List<MyDTO> ls2 = new ArrayList<MyDTO>();
    for(Object o : ls){
        ls2.add((MyDTO) o);
    }

Also, first StackOverflow questing, sorry if im asking something dumb or in a bad way.

2 Answers2

0

You can't directly convert Object to MyDTO until unless myDAO.getSomethingFromDB(); is returning list of MyDTO

Learn more about ClassCastException here: https://docs.oracle.com/javase/8/docs/api/java/lang/ClassCastException.html Explanation of ClassCastException in Java

if you really want to convert to MyDTO then you need to create new MyDTO object then set the values to this object.

Nagaraju Chitimilla
  • 530
  • 3
  • 7
  • 23
0

There are probably a lot of ways to do this, here is one of those ways using Java Streams:

List<MyObject> objects = // Get objects from database

List<MyDto> dtos = objects.stream().map(myObj -> {
            MyDto newDto = new MyDto();

            // Set your properties here, in this example i'm setting a name and description:
            newDto.setName(myObj.getName());
            newDto.setDescription(myObj.getDescription());
            // Repeat for every property

            return newDto;
        })
        .collect(Collectors.toList());

I am using the map function to create a new DTO with the same properties as my object in the list.

P. Protas
  • 416
  • 4
  • 15