0

I have enum:

public enum MyEnum {

 ONE, TWO;

}

And i would like to map String from DTO into this Enum. How to do it?

I tried like that:

@Mapper
interface MyEnumMapper {
 MyClass map(MyDTO response);

 @ValueMapping(target = "ONE", source = "one-code")
 MyEnum toMyEnum(String value);

But its not working, any thoughts?

Kusangai2
  • 3
  • 2
  • Does this answer your question? [From string to enum using mapstruct](https://stackoverflow.com/questions/48570827/from-string-to-enum-using-mapstruct) – Toni Jun 20 '23 at 19:37

1 Answers1

0

This works:

public class MyClass {

  private MyEnum value;

  public MyEnum getValue() {
    return value;
  }

  public void setValue(MyEnum value) {
    this.value = value;
  }
}
public class MyDTO {

  private String value;

  public String getValue() {
    return value;
  }

  public void setValue(String value) {
    this.value = value;
  }
}
public enum MyEnum {

  ONE, TWO;

}

@Mapper(componentModel = "spring")
public interface MyDTOMapper {

  @Mapping(source = "value", target = "value")
  MyClass toMyClass(MyDTO dto);

}

Check it with this:

  public static void main(String[] args) {

    MyDTOMapper myDTOMapper = new MyDTOMapperImpl();

    MyDTO myDTO = new MyDTO();
    myDTO.setValue("ONE");
    MyClass myClass = myDTOMapper.toMyClass(myDTO);
    System.out.println(myClass.getValue());
  }

$> ONE

codependent
  • 23,193
  • 31
  • 166
  • 308