Search code examples
javamappingmapstruct

Mapstruct mapping - String to List<String>


I am struggling to map a string object from source(Relation.class) and to a List of target(RelationListDTO.class) .

Relation.java

   public class Relation {

    private String name;
    private String email;
    private String completeAddress;

    // getters and setters
}

RelationListDTO.java

public class RelationListDTO {
        private String name;
        private String email;
        private List<Address> address;

        // getters and setters
    }

Address.java

public class Address{
private String street;
private String city;
// getters and setters
}

Mapper class

@Mapper

public interface RelationMapper {

    @Mapping(source = "completeAddress", target = "address.get(0).city")
            RelationListDTO relationToListDto(Relation relation);
} 

But it is not working. Could anyone please help.


Solution

  • What you are trying to do using MapStruct is not possible. Because MapStruct doesn't work with run time objects. MapStruct only generated plain java code for mapping two beans. And I find your requirement is little unique. You have a list of Addresses but want to map only city from source object? You can still do like this

    @Mapping( target = "address", source = "completeAddress")
    RelationListDTO relationToListDto(Relation relation);
    
    // MapStruct will know to use this method to map between a `String` and `List<Address>`
    default List<Address> mapAddress(String relation){
          //create new arraylist
          // create new AddressObject and set completeAddress to address.city
         // add that to list and return list
    
    }