问题
Long型数据返回前端,大于17位,js会丢失精度
解决方法
Json序列化的时候,将Long型转换为String类型
实现方式
自定义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); }
增加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); } }; }
注册
@Configuration public class SpringMvcConfiguration implements WebMvcConfigurer { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.forEach(CustomMessageConverterWrapper.objectMapperWrapper()); } }
本文由 Ivan Dong 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: Mar 21, 2023 at 09:26 am