mapstruct 高级用法

1、doTrim函数,toJsonString函数、自定义java函数(工具类见附录)

import com.dm.bs.model.vo.BsFieldTransResult;
import com.dm.bs.model.vo.BsFieldTransVO;
import com.dm.bs.repository.entity.BsFieldTrans;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;

/**
 * BsFieldTrans转换器
 */
@Mapper(uses = {TypeConversionWorker.class})
public interface BsFieldTransMapping {
    BsFieldTransMapping INSTANCE = Mappers.getMapper(BsFieldTransMapping.class);

    @Mapping(target = "targetUrl",source = "targetUrl",qualifiedByName = "doTrim")
    @Mapping(target = "transKey",source = "transKey",qualifiedByName = "toJsonString")
    @Mapping(target = "transVal",source = "transVal",qualifiedByName = "toJsonString")
    @Mapping(target = "relatedField", expression = "java(typeConversionWorker.generateRelatedField(bsFieldTransVO.getTransKey(), bsFieldTransVO.getTransVal()))") //使用工具类处理
    BsFieldTrans transToBsFieldTrans(BsFieldTransVO bsFieldTransVO);

    @Mapping(target = "relatedField",source = "relatedField",qualifiedByName = "listStr2CommaStr")
    BsFieldTransResult transToBsFieldTransResult(BsFieldTrans bsFieldTrans);
}

2、

 

附录:

1、转换工具类

import com.dm.bs.model.vo.TransKeyVO;
import com.dm.bs.model.vo.TransValVO;
import com.dm.bs.util.JacksonUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import org.mapstruct.Named;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Mapping通用转换
 */
@Component
@Named("TypeConversionWorker")
public class TypeConversionWorker {
    /**
     * 对象转json字符串
     *
     * @param obj
     * @return
     */
    @Named("toJsonString")
    public String toJsonString(Object obj) {
        if (Objects.isNull(obj)) {
            return null;
        }
        return JacksonUtil.toJsonString(obj);
    }

    /**
     * 去空格
     *
     * @param str
     * @return
     */
    @Named("doTrim")
    public String doTrim(String str) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        return str.trim();
    }

    /**
     * 字符串转List对象
     *
     * @param str
     * @return
     */
    @Named("toStrList")
    public List<String> toStrList(String str) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        return JacksonUtil.jsonToObjByTypeRf(str, new TypeReference<List<String>>() {
        });
    }

    /**
     * json字符串转换为Map
     *
     * @param obj
     * @return
     */
    @Named("toStrObjMap")
    public Object toStrObjMap(Object obj) {
        if (Objects.isNull(obj)) {
            return null;
        }
        return JacksonUtil.jsonToObjByTypeRf(obj.toString(), new TypeReference<Map<String, Object>>() {
        });
    }

    /**
     * jsonLsit转换为逗号隔开形式
     *
     * @param obj
     * @return
     */
    @Named("listStr2CommaStr")
    public String listStr2CommaStr(Object obj) {
        if (Objects.isNull(obj)) {
            return null;
        }
        List<String> strings = JacksonUtil.jsonToObjByTypeRf(obj.toString(), new TypeReference<List<String>>() {
        });
        if (strings != null) {
            return String.join(",", strings);
        }
        return null;
    }

    /**
     * BsFieldTransMapping生成relatedField内容
     */
    @Named("generateRelatedField")
    public String generateRelatedField(List<TransKeyVO> transKey, List<TransValVO> transVal) {
        List<String> relatedFieldList = new ArrayList<>();
        if (transKey != null && transKey.size() > 0) {
            transKey.forEach(k -> relatedFieldList.add(k.getCurrentKey()));
        }
        if (transVal != null && transVal.size() > 0) {
            transVal.forEach(v -> relatedFieldList.add(v.getTargetKey()));
        }
        return JacksonUtil.toJsonString(relatedFieldList);
    }

    /**
     * BsFieldTransMapping生成relatedField内容
     */
    @Named("getParentScope")
    public String getParentScope(String targetScope) {
        String[] split = targetScope.split("\\.");
        if (split.length == 1) {
            return "";
        }
        StringBuilder parentScope = new StringBuilder();
        for (int i = 0; i < split.length - 1; i++) {
            parentScope.append(split[i]);
            if (i < split.length - 2) {
                parentScope.append(".");
            }
        }
        return parentScope.toString();
    }
}

2、工具类

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JacksonUtil {
    private static ObjectMapper mapper = new ObjectMapper();

    /**
     * 对象转json
     *
     * @param object
     * @return
     */
    public static String toJsonString(Object object) {
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error("...Err...Jackson转换字符串(String)过程失败:::", e);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * json转对象
     *
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T jsonToBean(String json, Class<T> clazz) {
        try {
            return mapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            log.error("...Err...Jackson转换对象(Object)过程失败:::", e);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 字符串转换为List
     *
     * @param listStr
     * @param typeReference new TypeReference<List<Object>>() {}
     * @param <T>
     * @return
     */
    public static <T> T jsonToObjByTypeRf(String listStr, TypeReference<T> typeReference) {
        try {
            return mapper.readValue(listStr, typeReference);
        } catch (JsonProcessingException e) {
            log.error("...Err...Jackson转换Object过程失败:::", e);
            e.printStackTrace();
        }
        return null;
    }
}

 

posted @ 2020-11-06 09:25  songjn  阅读(13300)  评论(0编辑  收藏  举报