SpringBoot全局配置Long转String,解决前端接收时精度丢失的问题


springboot中WebMvcConfigurationSupport、WebMvcConfigurationAdapter区别
@EnableWebMvc如何禁止@EnableAutoConfiguration

第一种:直接对SimpleModule对象配置,避免其他地方的Jackson配置被覆盖的问题

@Configuration
public class JsonModuleConfig extends SimpleModule {
    public JsonModuleConfig() {
      //super(JsonModuleConfig.class.getName());
      this.addSerializer(Long.class, ToStringSerializer.instance);
      this.addSerializer(Long.TYPE, ToStringSerializer.instance);
    }
}

第二种:如果使用了自己的框架,这里的配置会导致自己框架的jackson配置失效

会根据扫描到的配置类顺序加载,如果匹配到第一个,则放弃后续的配置,所以自己的框架如果有配置Jackson配置的话,使用这个方法会导致原有配置被覆盖

@EnableWebMvc
@Configuration
public class WebDataConvertConfig implements WebMvcConfigurer {
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
      MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
      ObjectMapper objectMapper = new ObjectMapper();
      /**
       * 序列换成json时,将所有的long变成string
       * 因为js中得数字类型不能包含所有的java long值
       */
      SimpleModule simpleModule = new SimpleModule();
      simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
      simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
      simpleModule.addSerializer(BigInteger.class, ToStringSerializer.instance);

      // 反序列化时忽略多余字段
      objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

      // 注册
      objectMapper.registerModule(simpleModule);
      jackson2HttpMessageConverter.setObjectMapper(objectMapper);
      converters.add(jackson2HttpMessageConverter);
    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM