MapStruct:如何使用mapstruct将字符串转换为字节[]

问题描述 投票:2回答:2

在我的dto课堂上:

private String password;

在我的模型班上:

private byte[] password;

我想使用mapStruct将String转换为byte []。有人可以帮忙

提前感谢。

spring-boot mapping mapstruct
2个回答
2
投票

最好是提供一种在Stringbyte[]之间映射的默认方法。

例如:

@Mapper
public MyMapper {

    Model fromDto(Dto dto);

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

}

使用此方法,MapStruct将自动为DtoModel之间的所有其他字段执行操作,并将Stringbyte[]之间的映射保留为toBytes方法。


-1
投票

假设您有此类。

public class Source {

  private String password;

  //getters and setters

}

public class Destination {

  private byte[] password;

  //getters and setters

}

您可以创建自定义映射器。

@Mapper
public abstract class MyMapper {

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

然后

MyMapperImpl mapper = new MyMapperImpl();
Destination dest = mapper.sourceToDest(source);
© www.soinside.com 2019 - 2024. All rights reserved.