【问题标题】:MapStruct : How to convert String to byte[] using mapstructMapStruct:如何使用 mapstruct 将 String 转换为 byte[]
【发布时间】:2020-02-27 05:41:42
【问题描述】:

在我的 dto 类中:

private String password;

在我的模型类中:

private byte[] password;

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

提前致谢。

【问题讨论】:

    标签: spring-boot mapping mapstruct


    【解决方案1】:

    最好为Stringbyte[] 之间的映射提供默认方法。

    例如:

    @Mapper
    public MyMapper {
    
        Model fromDto(Dto dto);
    
        default byte[] toBytes(String string) {
            return string != null ? string.getBytes() : null;
        }
    
    }
    

    这样,您将让 MapStruct 自动为您在 DtoModel 之间的所有其他字段执行操作,并将 Stringbyte[] 之间的映射留给 toBytes 方法。

    【讨论】:

      【解决方案2】:

      假设你有这个类。

      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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-21
        • 2021-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-28
        • 1970-01-01
        • 2020-07-05
        相关资源
        最近更新 更多