javadozer

How can I tell Dozer to bypass mapping null or empty string values per field using the programming api?


The faq explains how to do this in XML. This shows how to do it per class using the API. The problem is you have to set it on on the class. What if I only want it on one field? Is this possible?


Solution

  • I was able to accomplish what I needed by creating my own custom converters for this. Here's the code:

    import org.apache.commons.lang.StringUtils;
    import org.dozer.DozerConverter;
    
    public class IfNotBlankConverter extends DozerConverter<String, String> {
    
        public IfNotBlankConverter() {
            super(String.class, String.class);
        }
    
        private String getObject(String source, String destination) {
            if (StringUtils.isNotBlank(source)) {
                return source;
            } else {
                return destination;
            }
        }
    
        @Override
        public String convertTo(String source, String destination) {
            return getObject(source, destination);
        }
    
        @Override
        public String convertFrom(String source, String destination) {
            return getObject(source, destination);
        }
    }
    

    Second one:

    import org.dozer.DozerConverter;
    
    public class IfNotNullConverter extends DozerConverter<Object, Object> {
    
        public IfNotNullConverter() {
            super(Object.class, Object.class);
        }
    
        @Override
        public Object convertTo(Object source, Object destination) {
            return getObject(source, destination);
        }
    
        @Override
        public Object convertFrom(Object source, Object destination) {
            return getObject(source, destination);
        }
    
        private Object getObject(Object source, Object destination) {
            if (source != null) {
                return source;
            } else {
                return destination;
            }
        }
    
    }