springboot 序列化相关问题汇总(持续更新...)

一、序列化问题

没有过多的性能需求,建议使用spring内置的jackjson,安全上更有保障

(1)返回数据

  • 返回空字段
    /**
     * 处理空字段
     * @param builder
     * @return
     */
    @Bean
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        // 实例化objectMapper
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        return objectMapper;
    }
  • 处理js序列化数字串精度丢失问题
    @Bean("jackson2ObjectMapperBuilderCustomizer")
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        Jackson2ObjectMapperBuilderCustomizer customizer = jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder
                .serializerByType(Long.class, ToStringSerializer.instance)
                .serializerByType(Long.TYPE, ToStringSerializer.instance);

        return customizer;
    }

二、javax.validation.Valid 无法校验对象集合

  • 编写增强工具类
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.List;
import java.util.Set;

/**
 * @author yilv
 * @version 1.0
 * @description: 实体校验增强
 * @date 2022/11/16 15:21
 */
public class ValidateUtil {
    private static final Validator validator;

    static {
        ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
        validator = vf.getValidator();
    }

    /**
     * 反射校验内层元素
     *
     * @param list
     */
    public static <T> void innerValidate(List<T> list) {
        list.forEach(M -> {
            Set<ConstraintViolation<T>> validate = validator.validate(M);
            if (validate.size() > 0) {
                throw new RuntimeException(validate.iterator().next().getMessage());
            }
        });
    }

    /**
     * 反射校验内层元素
     *
     * @param object
     */
    public static <T> void innerValidate(T object) {
        Set<ConstraintViolation<T>> validate = validator.validate(object);
        if (validate.size() > 0) {
            throw new RuntimeException(validate.iterator().next().getMessage());
        }
    }
}

三、com.baomidou.mybatisplus.extension.service.IService#updateById 设置字段为null,失效

  • mp的updateById 操作默认会过滤null值,你可以设置忽略该更新策略
    @TableField(value = "xxx",updateStrategy = FieldStrategy.IGNORED)

你可能感兴趣的:(spring,boot,后端,java)