Long返回前段丢失精度

package com.tourism.sms.contact.message.init.configure;

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.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import javax.servlet.MultipartConfigElement;
import java.util.List;

/**
 * 解决前台返回Long类型精度损失的问题
 * @author 三多
 * @Time 2019/3/25
 */
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
    /**
     * 解决前端解析Long丢精度的问题
     * @param converters
     */
    @Override
    public void configureMessageConverters(List> converters) {
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        /**
         * 序列换成json时,将所有的long变成string
         * 因为js中得数字类型不能包含所有的java long值
         */
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        converters.add(jackson2HttpMessageConverter);
    }


    /**
     * 解决 swagger-ui404问题
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

}

WebMvcConfigurerAdapter已过时,使用WebMvcConfigurationSupport或者WebMvcConfigurer来代替

 

如果上面全局修改失效采用下面注解模式,需要每个字段都添加

注解

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

 ... 
@JsonSerialize(using = ToStringSerializer.class) 
private Long taskSn;

 

 上面的方式只能解决返回前段是类对象的时候,或者是类列表的时候没问题,如果是多表联查会失效,可以采用sql修改类型

CAST(sm.BASE_ID AS CHAR) as baseId,

你可能感兴趣的:(spring-mvc,Long)