Mapstruct mapping Boolean to String

11,090

Solution 1

Analogous to Map Struct Reference#Invoking Other Mappers, you can define (your Helper) class like:

public class BooleanYNMapper {

    public String asString(Boolean bool) {
        return null == bool ?
            null : (bool ? 
                "Y" : "N"
            );
    }

    public Boolean asBoolean(String bool) {
        return null == bool ?
            null : (bool.trim().toLowerCase().startsWith("y") ?
                Boolean.TRUE : Boolean.FALSE
            );
    }
}

..and then use it in (the hierarchy of) your mappers:

@Mapper(uses = BooleanYNMapper.class)
interface MyMapper{
    Target map(Source s);
    //and even this will work:
    Source mapBack(Target t);
}

Solution 2

If I remember correctly, you just have to provide a custom type conversion concrete method.
Let's say you're still using abstract classes for Mappers.

@Mapper
public abstract class YourMapper {
    @Mappings(...)
    public abstract Target sourceToTarget(final Source source);

    public String booleanToString(final Boolean bool) {
        return bool == null ? "N" : (bool ? "Y" : "N");
    }
}

This should be possible even with Java 8 Interface default methods.

Share:
11,090
Sridhar
Author by

Sridhar

Updated on June 04, 2022

Comments

  • Sridhar
    Sridhar almost 2 years

    I have several Boolean fields in my model class (source). The target field in my DTO class is String. I need to map true as Y and false as N. There are more than 20 Boolean fields and right now I am using 20+ @Mapping annotation with expression option, which is overhead. There must be a simple way or solution that I am not aware. Can anyone help to simplify this?

    I am using mapstruct version 1.2.0.Final

    Source.java

    class Source{
      private Boolean isNew;
      private Boolean anyRestriction;
      // several Boolean fields
    }
    

    Target.java

    class Target{
      private String isNew;
      private String anyRestriction;
    }
    

    Helper.java

    class Helper{
      public String asString(Boolean b){
        return b==null ? "N" : (b ? "Y" : "N");
      }
    }
    

    MyMapper.java

    @Mapper interface MyMapper{
      @Mappings(
        @Mapping(target="isNew", expression="java(Helper.asString(s.isNew()))"
        // 20+ mapping like above, any simple way ? 
      )
      Target map(Source s);
    }
    
  • Filip
    Filip about 5 years
    Yes you can do this with a default method or even a default static method on the interface
  • Sridhar
    Sridhar about 5 years
    Both the answers are working. I accepted @xerx593’s as correct because I can reuse the BooleanYNMapper in some other mapper interface. Thanks.