问题描述
由于javascript的number类型问题,前端使用number接收后端的long类型时,后两位会变成00,导致前后端id不一致
解决思路
将后端的Long类型,在json序列化时,返回的类型为string类型
解决方案1
使用注解
@JsonSerialize(using=ToStringSerializer.class)
private Long id;
解决方案2
全局处理,添加 http message转换器
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.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
/**
* 序列化json时,将所有的long变成string
* 因为js中得数字类型不能包含所有的java long值
*/
@Override
public void configureMessageConverters(List> converters) {
MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule simpleModule=new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
jackson2HttpMessageConverter.setObjectMapper(objectMapper);
converters.add(0,jackson2HttpMessageConverter);
}
}