今天在学习的时候发现,后端Long类型的Id过长的话,传到前端后导致精度丢失,做一些删除编辑等操作时,就会导致操作失败,我们只需要将Long类型的数据,转为Sting类型传到前端即可,这边学了两个调整方法,方便以后使用。
方法1:使用注解 @JsonSerialize(using = ToStringSerializer.class)
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
方法2:全局配置Long类型数据转为String类型返回前端
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;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder){
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
return objectMapper;
}
}