Mapstruct mapping Boolean to String
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.
Sridhar
Updated on June 04, 2022Comments
-
Sridhar almost 2 years
I have several
Boolean
fields in my model class (source). The target field in my DTO class isString
. I need to maptrue
asY
andfalse
asN
. There are more than 20Boolean
fields and right now I am using 20+@Mapping
annotation withexpression
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
version1.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 about 5 yearsYes you can do this with a default method or even a default static method on the interface
-
Sridhar about 5 yearsBoth the answers are working. I accepted @xerx593’s as correct because I can reuse the BooleanYNMapper in some other mapper interface. Thanks.