在使用Spring Boot开发Web应用时,如果后端返回的长整型数据(如Java中的long或Long类型)在前端JavaScript中处理时出现精度损失,这通常是由于JavaScript对数字的处理能力有限(JavaScript中所有数字都是以64位浮点数表示的,这会导致一些非常大的整数精度丢失)。为了解决这个问题,可以采取以下几种方法:
1. 使用字符串格式返回长整型数据
将长整型数据以字符串形式返回给前端,这样可以避免JavaScript在解析为数字时丢失精度。
Spring Boot 后端代码示例:前端 JavaScript 代码示例:
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/data")
public ResponseEntity<Map<String, Object>> getData() {
Map<String, Object> response = new HashMap<>();
long longValue = 1234567890123456789L;
response.put("longValueAsString", String.valueOf(longValue));
return ResponseEntity.ok(response);
}
}前端 JavaScript 代码示例:
fetch('/api/data')
.then(response => response.json())
.then(data => {
const longValueAsString = data.longValueAsString;
console.log(longValueAsString); // 正确输出长整型数据
})
.catch(error => console.error('Error:', error));2. 使用BigInt类型(如果前端环境支持)
在ES2020中,JavaScript引入了BigInt类型,它可以安全地表示任意大小的整数。如果前端环境支持BigInt,可以直接将长整型数据作为字符串传递给前端,并在前端转换为BigInt。
前端 JavaScript 代码示例:
fetch('/api/data') // 假设后端仍返回字符串形式的长整型数据
.then(response => response.json())
.then(data => {
const longValueAsString = data.longValueAsString;
const longValueAsBigInt = BigInt(longValueAsString);
console.log(longValueAsBigInt); // 正确输出BigInt类型的大整数
})
.catch(error => console.error('Error:', error));3. 在实体类的Long属性上加@JsonSerialize注解
在实体类中,通过加@JsonSerialize(using = ToStringSerializer.class)将长整型属性序列化为字符串:
package com.wanmait.bootdemo.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
public class Blog {
@JsonFormat
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
private String title;
}
4. 使用JSON库进行自定义序列化
在Spring Boot中,可以使用Jackson或其他JSON库来自定义序列化行为,将长整型数据序列化为字符串。
配置Jackson序列化器:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//@JsonComponent
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(Long.class, ToStringSerializer.instance);
module.addSerializer(long.class, ToStringSerializer.instance);
mapper.registerModule(module);
return mapper;
}
}这样配置后,Spring Boot会自动将Long和long类型的字段序列化为字符串。
总结
字符串格式:简单有效,兼容性好。
BigInt:适用于现代浏览器,可以处理任意大小的整数。
个别属性为Long类型,可以直接在类的属性上加注解即可。
自定义序列化:需要在后端进行额外配置,但可以统一处理所有长整型数据。
选择哪种方法取决于你的具体需求。

0条评论
点击登录参与评论