web层统一处理Long转String问题

web层统一处理Long转String问题
有些字段或者方法并不需要Long转String
那么在字段或者方法上加注解@SkipLongToString,Long不会转String

InterceptorConfig


import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    /**
     * 拦截器转换
     * web层统一处理Long转String问题
     * @param converters 需要转换的对象
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        System.out.println("开始配置Jackson消息转换器及自定义序列化器...");
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = jackson2HttpMessageConverter.getObjectMapper();
        SimpleModule simpleModule = new SimpleModule();

        // 使用自定义的序列化器,并根据注解决定是否转换为String(针对字段注解以及方法注解情况)
        simpleModule.addSerializer(Long.class, new CustomLongToStringSerializer());
        simpleModule.addSerializer(Long.TYPE, new CustomLongToStringSerializer());

        objectMapper.registerModule(simpleModule);
        jackson2HttpMessageConverter.setObjectMapper(objectMapper);

        converters.add(0, jackson2HttpMessageConverter);
        System.out.println("完成配置Jackson消息转换器及自定义序列化器.");
    }
}

CustomLongToStringSerializer

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import java.io.IOException;
import java.lang.reflect.Method;

public class CustomLongToStringSerializer extends JsonSerializer<Long> implements ContextualSerializer {

    private boolean skipConversion = false;

    @Override
    public void serialize(Long value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (skipConversion) {
            // 如果设置了跳过转换,按Jackson默认方式序列化Long类型(即数字形式)
            gen.writeNumber(value);
        } else {
            gen.writeString(String.valueOf(value));
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        if (property!= null) {
            // 检查属性所在方法是否带有 @SkipLongToString 注解
            Method method = getMethodFromProperty(property);
            if (method!= null && method.isAnnotationPresent(SkipLongToString.class)) {
                this.skipConversion = true;
                return this;
            }

            // 检查属性是否带有 @SkipLongToString 注解(针对普通属性情况)
            SkipLongToString skipAnnotation = property.getAnnotation(SkipLongToString.class);
            if (skipAnnotation!= null) {
                this.skipConversion = true;
            } else {
                this.skipConversion = false;
            }
        }
        return this;
    }

    private Method getMethodFromProperty(BeanProperty property) {
        try {
            Class<?> declaringClass = property.getMember().getDeclaringClass();
            String methodName = getMethodNameFromProperty(property);
            for (Method method : declaringClass.getDeclaredMethods()) {
                if (method.getName().equals(methodName)) {
                    return method;
                }
            }
        } catch (Exception e) {
            // 可以添加适当的日志记录异常情况
        }
        return null;
    }

    private String getMethodNameFromProperty(BeanProperty property) {
        // 这里简单通过属性名推测方法名,可根据实际情况调整更准确的获取方式
        return "get" + property.getName().substring(0, 1).toUpperCase() + property.getName().substring(1);
    }
}

SkipLongToString


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface SkipLongToString {
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值