Table of contents
1. Solve the problem of loss of precision when the backend responds to the frontend
2. Freemark BigDecimal data display accuracy loss problem
3. The problem of loss of value precision when the method is called by the front end
1. Solve the problem of loss of precision when the backend responds to the frontend
- Solution 1: Annotations are marked on the corresponding fields in the project, and Long is automatically converted to String when Json is serialized.
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
- Solution 2: Global configuration. The id field of each entity class needs to be annotated with @JsonSerialize, which is a bit cumbersome. We can first modify the Jackson converter to achieve global unified processing of Long type fields. As follows:
@EnableWebMvc
@Configuration
public class MvcConfig implements WebMvcConfigurer {
/**
* 重写Jackson转换器
* Long类型转String类型
*
* 解决前端Long类型精度丢失问题(js解析只能解析到16位)
*
* @param converters
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter jackson2HttpMessageConverter =
new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(BigInteger.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
jackson2HttpMessageConverter.setObjectMapper(objectMapper);
converters.add(jackson2HttpMessageConverter);
converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
}
}
- Solution 3: Global configuration serialization returns JSON processing
@Configuration
public class JacksonConfig {
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder)
{
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
// 全局配置序列化返回 JSON 处理
SimpleModule simpleModule = new SimpleModule();
//JSON Long ==> String
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
return objectMapper;
}
}
2. Freemark BigDecimal data display accuracy loss problem
${数据?c} 就是在后面添加?c
3. The problem of loss of value precision when the method is called by the front end
function fa(id){
//用BigInt数据类型转换一次即可
let ids=BigInt(id)
}