Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

spring boot 项目,是否可以通过统一配置来使得返回给前端的Long类型数据都转为String类型?

  1. User

    spring boot 项目,是否可以通过统一配置来使得返回给前端的Long类型数据都转为String类型?

  2. Assistant

    可以通过自定义一个全局的返回处理器来实现返回 Long 类型数据转为 String 类型的操作。具体实现步骤如下:

    1. 创建一个返回值统一处理器类,命名为 ResultBodyAdvice,并实现 ResponseBodyAdvice 接口。
    @ControllerAdvice(basePackages = "com.example.demo")
    public class ResultBodyAdvice implements ResponseBodyAdvice<Object> {
        
        @Override
        public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
            return true; //拦截所有Controller方法的返回值
        }
    
        @Override
        public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                ServerHttpResponse response) {
            if (body instanceof Long) {
                return String.valueOf(body);
            }
            return body;
        }
        
    }
    
    1. 在 ResultBodyAdvice 类上使用 @ControllerAdvice 注解,并指定需要拦截的 Controller 包名。

    2. 在 beforeBodyWrite 方法中判断返回值的类型,如果是 Long 类型,则转为 String 类型返回。否则,直接返回原始类型。

    3. 重新启动 Spring Boot 项目,即可看到所有返回 Long 类型数据都被转换为 String 类型。

    注意:使用 beforeBodyWrite 方法修改响应数据时,一定要使用同样的 Content-Type 类型返回,否则会出现类型转换错误。例如,如果响应类型为 application/json,返回值类型为 String,那么一定要使用 response.getHeaders().setContentType(MediaType.APPLICATION_JSON); 设置响应类型为 application/json。

  3. User

    你有误解,Long可能是返回数据的某个字段的类型,而不是返回类型本身

  4. Assistant

    非常抱歉,我的理解有误。如果需要统一将返回数据中的 Long 类型字段转换为 String 类型,可以使用自定义 Jackson 序列化器来实现。具体实现步骤如下:

    1. 创建一个自定义的 Jackson 序列化器,继承 JsonSerializer 类。
    public class LongToStringSerializer extends JsonSerializer<Long> {
    
        @Override
        public void serialize(Long value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeString(value.toString());
        }
      
    }
    
    1. 创建一个自定义注解 LongToString,用于标注需要转换为 String 类型的 Long 类型字段。
    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface LongToString {
    }
    
    1. 创建一个 Jackson 序列化模块,继承 SimpleModule 类,并注册自定义的序列化器。
    public class LongToStringModule extends SimpleModule {
    
        public LongToStringModule() {
            super();
            this.addSerializer(Long.class, new LongToStringSerializer());
        }
        
        @Override
        public void setupModule(SetupContext context) {
            context.appendAnnotationIntrospector(new LongToStringAnnotationIntrospector());
            super.setupModule(context);
        }
        
        static class LongToStringAnnotationIntrospector extends JacksonAnnotationIntrospector {
    
            @Override
            public Object findSerializer(Annotated annotated) {
                if (annotated.hasAnnotation(LongToString.class)) {
                    return new LongToStringSerializer();
                }
                return super.findSerializer(annotated);
            }
            
        }
        
    }
    
    1. 在 Spring Boot 的配置文件中注册自定义的 Jackson 序列化模块。
    spring.jackson.modules:
      - com.example.demo.LongToStringModule
    
    1. 在需要转换为 String 类型的 Long 类型字段上打上 @LongToString 注解。
    public class User {
        
        private Long userId;
       
        @LongToString
        private Long phone;
    
        //省略getter和setter方法
    }
    
    1. 重新启动 Spring Boot 项目,即可看到所有加上 @LongToString 注解的 Long 类型字段被转换为 String 类型。

    注意:如果需要在所有返回数据中统一将 Long 类型转换为 String 类型,可以使用 @JsonSerialize(using = LongToStringSerializer.class) 注解标注在返回类型或对应的属性上。但这种方式需要在每个需要转换的地方都添加注解,不太方便,不推荐使用。