Spring boot + vue 项目前后端分离,后端接口返回Long类型给前端,精度丢失问题

使用spring boot + vue做项目时,当后端接口传Long类型数据给前端当时候,精度丢失,导致数据不准确。

解决方案:

在JavaBean上之间加上下面的注解  (spring boot默认使用Jackson类库),对象序列化成JSON时,将Long转成String

import com.fasterxml.jackson.databind.annotation.JsonSerialize; 

import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; 



@JsonSerialize(using = ToStringSerializer.class) 

Long id

附:Jackson的ToStringSerializer源码

public class ToStringSerializer extends StdSerializer<Object> {
    public static final ToStringSerializer instance = new ToStringSerializer();

    public ToStringSerializer() {
        super(Object.class);
    }

    public ToStringSerializer(Class<?> handledType) {
        super(handledType, false);
    }

    public boolean isEmpty(SerializerProvider prov, Object value) {
        return value.toString().isEmpty();
    }

    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeString(value.toString());
    }

    public void serializeWithType(Object value, JsonGenerator g, SerializerProvider provider, TypeSerializer typeSer) throws IOException {
        WritableTypeId typeIdDef = typeSer.writeTypePrefix(g, typeSer.typeId(value, JsonToken.VALUE_STRING));
        this.serialize(value, g, provider);
        typeSer.writeTypeSuffix(g, typeIdDef);
    }

    public JsonNode getSchema(SerializerProvider provider, Type typeHint) throws JsonMappingException {
        return this.createSchemaNode("string", true);
    }

    public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException {
        this.visitStringFormat(visitor, typeHint);
    }
}

若想自定义类型可以重写 JsonSerializer serialize方法。

如Date转成Long类型的时间戳

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
 
import java.io.IOException;
import java.util.Date;
 
public class CustomSerializer extends JsonSerializer<Date> {
    @Override
    public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
        jsonGenerator.writeNumber(date.getTime()/1000);
    }
}





// 创建时间
    @JsonSerialize(using = CustomSerializer .class)
    private Date createTime;

---------------------

本文来自 翻墨 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/qq_37749185/article/details/81131414?utm_source=copy 

2、如果使用FastJson,在JavaBean中使用FastJson注解
 

import com.alibaba.fastjson.annotation.JSONField;

import com.alibaba.fastjson.serializer.ToStringSerializer; 



@JSONField(serializeUsing= ToStringSerializer.class) 

private Long id; 

附:FastJson的ToStringSerializer源码

public class ToStringSerializer implements ObjectSerializer {
    public static final ToStringSerializer instance = new ToStringSerializer();

    public ToStringSerializer() {
    }

    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        SerializeWriter out = serializer.out;
        if (object == null) {
            out.writeNull();
        } else {
            String strVal = object.toString();
            out.writeString(strVal);
        }
    }
}

如果想扩展该注解,需要通过实现ObjectSerializer接口来完成

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Jackson类库有很多注解,可以让我们快速建立Java和JSON的关系,详细可以参考:https://github.com/FasterXML/jackson-annotations/wiki/Jackson-Annotations

有关FastJson @JSONField的使用,可以参考:https://www.w3cschool.cn/fastjson/fastjson-jsonfield.html

 

好的,这是一个简单的Spring Boot + Vue前端分离项目,供您参考: 后端(Spring Boot): 1. 创建一个Spring Boot项目,添加Web和JPA依赖 2. 配置数据库连接信息 3. 创建实体类和对应的Repository接口 4. 创建Controller类,实现对应的API接口 前端(Vue): 1. 安装Vue CLI,创建一个Vue项目 2. 安装Axios,用于发送HTTP请求 3. 创建Vue组件,实现对应的页面功能 4. 在组件中使用Axios发送请求,获取后端数据 具体可以参考以下代码: 后端代码: 实体类: ``` @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String email; // getter和setter方法省略 } ``` Repository接口: ``` public interface UserRepository extends JpaRepository<User, Long> { } ``` Controller类: ``` @RestController @RequestMapping("/api") public class UserController { @Autowired private UserRepository userRepository; @GetMapping("/users") public List<User> getUsers() { return userRepository.findAll(); } } ``` 前端代码: 安装Axios: ``` npm install axios ``` Vue组件: ``` <template> <div> <h2>用户列表</h2> <table> <thead> <tr> <th>ID</th> <th>姓名</th> <th>邮箱</th> </tr> </thead> <tbody> <tr v-for="user in users" :key="user.id"> <td>{{ user.id }}</td> <td>{{ user.name }}</td> <td>{{ user.email }}</td> </tr> </tbody> </table> </div> </template> <script> import axios from 'axios'; export default { data() { return { users: [], }; }, mounted() { axios.get('/api/users').then((response) => { this.users = response.data; }); }, }; </script> ``` 以上代码仅供参考,具体实现可以根据自己的实际情况进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值