user3611772
user3611772

Reputation: 35

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.

Upvotes: 2

Views: 14711

Answers (2)

Marco Martins
Marco Martins

Reputation: 185

Not sure if this was possible at the time of the accepted answer but I had the same problem as you and ended up doing it this way.

@Mapper(imports = Collections.class)
public interface RelationMapper {
    @Mapping(expression = "java(Collections.singletonList(relation.getCompleteAddress()))", target = "address")
            RelationListDTO relationToListDto(Relation relation);
}

Upvotes: 1

Naveen
Naveen

Reputation: 473

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

}

Upvotes: 7

Related Questions