目录
一、背景
我在项目中前辈的代码中发现了在使用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)就是想字符串转换为数字这样就可以不在业务里面频繁的去做类型转换了