Springboot/MVC序列化Long型为String
in develop with 0 comment

Springboot/MVC序列化Long型为String

in develop with 0 comment

问题

Long型数据返回前端,大于17位,js会丢失精度

解决方法

Json序列化的时候,将Long型转换为String类型

实现方式

  1. 自定义Jackson ObjectMapper,增加转换Module

      /**
    * registerLongSerializer
    *
    * <p>Handle Long Format to String
    *
    * @author Created by ivan at 下午2:53 2020/1/10.
    */
      public static void registerLongSerializer(ObjectMapper objectMapper) {
     SimpleModule long2StringModule = new SimpleModule();
     // Handle long To String
     long2StringModule.addSerializer(Long.class, ToStringSerializer.instance);
     objectMapper.registerModule(long2StringModule);
      }
  2. 增加Converter Function,用于替换MappingJackson2HttpMessageConverter中的ObjectMapper

      public static Consumer<HttpMessageConverter<?>> objectMapperWrapper() {
     return converter -> {
       if (converter instanceof MappingJackson2HttpMessageConverter httpMessageConverter) {
         ObjectMapper objectMapper = httpMessageConverter.getObjectMapper();
         JsonHelper.registerLongSerializer(objectMapper);
         httpMessageConverter.setObjectMapper(objectMapper);
       }
     };
      }
  3. 注册

    @Configuration
    public class SpringMvcConfiguration implements WebMvcConfigurer {
    
      @Override
      public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
     converters.forEach(CustomMessageConverterWrapper.objectMapperWrapper());
      }
    }
Comments are closed.