问题描述:
当实体类中的字段为Long类型,且值超过前端js显示的长度范围时会导致前端回显错误。
后端JSON字符串{“id”: 1540951455810646018, “name”: “张三”, …},前端通过data.id获取id时,id的值变成了1540951455810646000,id的位数精度缺失了。
方法1,局部设置,pojo类的字段添加以下属性,
@JsonFormat 用来表示json序列化的一种格式或者类型,shap表示序列化后的一种类型
@JsonFormat(shape = JsonFormat.Shape.STRING)
方法2,全局设置,推荐
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.boot.jackson.JsonComponent;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
/**
* Spring MVC Json 配置
*/
@JsonComponent
public class JsonConfig {
/**
* 添加 Long 转 json 精度丢失的配置
*/
@Bean
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
SimpleModule module = new SimpleModule();
module.addSerializer(Long.class, ToStringSerializer.instance);
module.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(module);
return objectMapper;
}
}