MapStruct : How to convert String to byte[] using mapstruct

Viewed 1705

In My dto class :

private String password;

In my model class:

private byte[] password;

I want to convert String to byte[] using mapStruct. Can someone help

Thanks in advance.

2 Answers

Best would be to provide a default method for mapping between String and byte[].

For example:

@Mapper
public MyMapper {

    Model fromDto(Dto dto);

    default byte[] toBytes(String string) {
        return string != null ? string.getBytes() : null;
    }

}

With this you will have MapStruct do automatic for all of your other fields between Dto and Model and leave the mapping between String and byte[] to the toBytes method.

Suppose you have this classes.

public class Source {

  private String password;

  //getters and setters

}

public class Destination {

  private byte[] password;

  //getters and setters

}

You can create a custom mapper.

@Mapper
public abstract class MyMapper {

  public Destination sourceToDest(Source source) {
    Destination dest = new Destination();
    dest.setPassword(source.getPassword().getBytes());
    return dest;
  }
}

Then

MyMapperImpl mapper = new MyMapperImpl();
Destination dest = mapper.sourceToDest(source);
Related