后端将Long类型的数据传给前端,前端可能会出现精度丢失的情况及其解决方案

第一步:定义转换类

类1:LongJsonSerializer.java
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * Long 类型字段序列化时转为字符串,避免js丢失精度
 * @author chenahaitong
 */
@Slf4j
public class LongJsonSerializer extends JsonSerializer<Long> {
     
    @Override
    public void serialize(Long value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
     
        String text = (value == null ? null : String.valueOf(value));
        if (text != null) {
     
            jsonGenerator.writeString(text);
        }
    }
}
类2:LongJsonDeserializer.java
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * 将字符串转为Long
 * @author chenhaitong
 */
@Slf4j
public class LongJsonDeserializer extends JsonDeserializer<Long> {
     

    @Override
    public Long deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
     
        String value = jsonParser.getText();
        try {
     
            return value == null ? null : Long.parseLong(value);
        } catch (NumberFormatException e) {
     
            log.error("解析长整形错误", e);
            return null;
        }
    }
}

第二步:实体类添加注解

import cn.ecpark.service.omp.api.helper.LongJsonDeserializer;
import cn.ecpark.service.omp.api.helper.LongJsonSerializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;

import java.io.Serializable;

/**
 * 用车大户返回实体
 *
 * @author chenhaitong
 * @date 2020/04/03 11:26
 */
@Data
public class FleetVo implements Serializable {
     

    private static final long serialVersionUID = -3659161298820068370L;
    /**
     * 唯一标识
     */
    @JsonSerialize(using = LongJsonSerializer.class)
    @JsonDeserialize(using = LongJsonDeserializer.class)
    private Long id;
}

第三步:实现方法展示

public static void main(String[] args) throws JsonProcessingException{
     
        FleetVo vo = new FleetVo();
        vo.setId(177170583434938112L);
        ObjectMapper objectMapper = new ObjectMapper();
        String value = objectMapper.writeValueAsString(vo);
        // 结果:{"id":"1177170583434938112"}
        System.out.println(value);
    }

结论:序列化时会触发注解的转换方法,实现Long转字符串,然后输出。延伸:其他类型亦然,比如:时间转Integer、浮点数或Double保留几位小数等等。

你可能感兴趣的:(java)