第一个类:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
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.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
/**
* @desc: webMvc配置
* @auth: zhangsy
* @data: 2019/9/20 10:09
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private HttpMessageConverters httpMessageConverters;
/**
* MappingJackson2HttpMessageConverter 实现了HttpMessageConverter 接口,
* httpMessageConverters.getConverters() 返回的对象里包含了MappingJackson2HttpMessageConverter
* @return
*/
@Bean
public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
return new MappingJackson2HttpMessageConverter(new JSONMapper());
}
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.addAll(httpMessageConverters.getConverters());
}
}
第二个类:JSONMapper.java
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
/**
* @desc: 类型转换:主要解决问题 将controller 返回的对象中long 类型转换为 string 类型返回给
* 前端,这样前端能看到 long 保存的真实的 数据
*
* @auth: zhangsy
* @data: 2019/9/20 9:57
*/
public class JSONMapper extends ObjectMapper {
/**
* @desc: 配置类型转换器
* @auth: zhangsy
* @data: 2019/9/20 10:09
* @return:
*/
public JSONMapper() {
super();
this.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true);
this.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);
this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
this.setSerializationInclusion(JsonInclude.Include.NON_NULL);
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
simpleModule.addSerializer(long.class, ToStringSerializer.instance);
registerModule(simpleModule);
}
}
另外一种简单的方法:
最后修改于 2020-03-02 17:26:20
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付

