【工具类】java中自写工具类在实体中直接使用注解进行数据类型转换

目录

一、背景

二、数字 将转字符串转换为整数,并且忽略0

三、字符串转换为整数

四、使用


 一、背景

我在项目中前辈的代码中发现了在使用lombok时,可以直接在某个属性上面做限制,然后我就发现这个前辈直接写了限制的工具类,我觉的挺方便的,所以记录一下;

二、数字 将转字符串转换为整数,并且忽略0

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.node.IntNode;
import com.fasterxml.jackson.databind.node.TextNode;

import java.io.IOException;
import java.util.Objects;

/**
 * 数字 转字符串转换为整数,并且忽略0
 * @author li
 */
public class IntAndIgnoreZeroConverter extends JsonDeserializer<Integer> {


    @Override
    public Integer deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        TreeNode treeNode = jsonParser.getCodec().readTree(jsonParser);
        if (treeNode != null) {
            if (treeNode instanceof IntNode) {
                if (Objects.equals(((IntNode) treeNode).intValue(), 0)){
                    return null;
                }
                return ((IntNode) treeNode).intValue();
            } else if (treeNode instanceof TextNode) {
                if (Objects.equals(((TextNode) treeNode).asText(), "0")){
                    return null;
                }
                return ((TextNode) treeNode).intValue();
            }

        }
        return null;
    }
}
三、字符串转换为整数
 
import com.fasterxml.jackson.databind.util.StdConverter;
import org.springframework.util.StringUtils;

/**
 * 字符串转换为整数
 * @author li
 */
public class StrToIntConverter extends StdConverter<String,Integer> {

    @Override
    public Integer convert(String value) {
        if (StringUtils.hasText(value)){
            return value.trim().isEmpty() ? null: Integer.valueOf(value);
        }
        return null;
    }
}
四、使用
@Data
@EqualsAndHashCode(callSuper = true)
public class MerchantMemberListReqDTO  extends PageVo {

    @ApiModelProperty(value = "行业类别(2级品类ID)")
    @JsonDeserialize(contentConverter = StrToIntConverter.class)
    private Integer categoryId;
    @ApiModelProperty(value = "会员名称")
    private String userName;
    @ApiModelProperty(value = "会员类型")
    private String memberTypeCode;
    @ApiModelProperty(value = "会员层级")
    @JsonDeserialize(contentConverter = StrToIntConverter.class)
    private Integer genesIndex;
}

其中  @JsonDeserialize(contentConverter = StrToIntConverter.class)就是想字符串转换为数字这样就可以不在业务里面频繁的去做类型转换了

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值