SpringBoot ResponseBody返回值处理的实现
1.SpringBootResponseBody返回值中null值处理
@PostMapping(path="/test",produces=MediaType.APPLICATION_JSON_VALUE)
publicObjecttest(){
JSONObjectjsonObject=newJSONObject();
jsonObject.put("test","test");
jsonObject.put("testnull",null);
ApiResponseVoapiResponseVo=newApiResponseVo();
apiResponseVo.setData(jsonObject);
apiResponseVo.setStatus(0);
returnapiResponseVo;
}
接口返回(想实现将testnull也进行返回
{
"data":{
"test":"test"
},
"status":0
}
importjava.nio.charset.Charset;
importjava.util.ArrayList;
importjava.util.List;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.http.MediaType;
importorg.springframework.http.converter.HttpMessageConverter;
importorg.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
importcom.alibaba.fastjson.serializer.SerializerFeature;
importcom.alibaba.fastjson.support.config.FastJsonConfig;
importcom.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
@Configuration
publicclassfastJsonConfigextendsWebMvcConfigurationSupport{
@Override
publicvoidconfigureMessageConverters(List>converters){
FastJsonHttpMessageConverterconverter=newFastJsonHttpMessageConverter();
FastJsonConfigconfig=newFastJsonConfig();
config.setSerializerFeatures(
//保留Map空的字段
SerializerFeature.WriteMapNullValue,
//将String类型的null转成""
//SerializerFeature.WriteNullStringAsEmpty,
//将Number类型的null转成0
//SerializerFeature.WriteNullNumberAsZero,
//将List类型的null转成[]
//SerializerFeature.WriteNullListAsEmpty,
//将Boolean类型的null转成false
//SerializerFeature.WriteNullBooleanAsFalse,
//避免循环引用
SerializerFeature.DisableCircularReferenceDetect
);
converter.setFastJsonConfig(config);
converter.setDefaultCharset(Charset.forName("UTF-8"));
ListmediaTypeList=newArrayList<>();
//解决中文乱码问题,相当于在Controller上的@RequestMapping中加了个属性produces="application/json"
mediaTypeList.add(MediaType.APPLICATION_JSON);
converter.setSupportedMediaTypes(mediaTypeList);
converters.add(converter);
}
}
2.拦截responsebody转json,对数据进行二次处理(字典转换做案例)
2.1>设置拦截器
importjava.nio.charset.StandardCharsets;
importjava.util.List;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.http.converter.HttpMessageConverter;
importorg.springframework.http.converter.StringHttpMessageConverter;
importorg.springframework.web.servlet.config.annotation.InterceptorRegistry;
importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;
importcom.alibaba.fastjson.serializer.SerializerFeature;
importcom.alibaba.fastjson.support.config.FastJsonConfig;
importcom.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
importcom.fintell.dp3.manager.interceptor.LogInterceptor;
@Configuration
publicclassWebMvcConfigurationimplementsWebMvcConfigurer{
@Override
publicvoidaddInterceptors(InterceptorRegistryregistry){
//自定义拦截器,添加拦截路径和排除拦截路径
registry.addInterceptor(getLogInterceptor()).addPathPatterns("/**");
}
@Bean
publicLogInterceptorgetLogInterceptor(){
returnnewLogInterceptor();
}
/**
*修改StringHttpMessageConverter默认配置&Json默认序列化方式(改这个方法)
*/
@Override
publicvoidconfigureMessageConverters(List>converters){
//创建fastJson消息转换器
FastJsonHttpMessageConverterfastConverter=newFastJsonHttpMessageConverter();
//创建配置类
FastJsonConfigfastJsonConfig=newFastJsonConfig();
//修改配置返回内容的过滤
fastJsonConfig.setSerializerFeatures(
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty
);
fastConverter.setFastJsonConfig(fastJsonConfig);
//将fastjson添加到视图消息转换器列表内
converters.add(fastConverter);
}
}
2.2>字典注解类
importjava.lang.annotation.ElementType;
importjava.lang.annotation.Retention;
importjava.lang.annotation.RetentionPolicy;
importjava.lang.annotation.Target;
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public@interfaceDict{
Stringtype();
}
2.3>序列化类
importjava.io.IOException; importjava.lang.reflect.Field; importorg.apache.commons.lang3.StringUtils; importorg.springframework.context.annotation.Configuration; importcom.fasterxml.jackson.core.JsonGenerator; importcom.fasterxml.jackson.databind.JsonSerializer; importcom.fasterxml.jackson.databind.ObjectMapper; importcom.fasterxml.jackson.databind.SerializerProvider; importlombok.extern.slf4j.Slf4j; @Slf4j @Configuration publicclassDictJsonSerializerextendsJsonSerializer
2.4>字典注解使用
@SuppressWarnings("serial")
@Builder
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
publicclassBizRuleDtoimplementsSerializable{
//指定使用哪种序列化
@JsonSerialize(using=DictJsonSerializer.class)
//指定字典(将被转换为{"code":"content","name":"contentname"}格式)
@Dict(type="content")
privateStringcontent;
}
3.其它补充(从容器中获取某个实例):如DictJsonSerializer需要通过service查询数据库获取字典
@Slf4j publicclassDictJsonSerializerextendsJsonSerializer
SpringUtils
importorg.springframework.beans.BeansException;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.ApplicationContextAware;
importorg.springframework.stereotype.Component;
@Component
publicclassSpringUtilsimplementsApplicationContextAware{
privatestaticApplicationContextctx;
/**
*获取bean
*/
@SuppressWarnings("unchecked")
publicstaticTgetBean(Stringid){
return(T)ctx.getBean(id);
}
/**
*按类型获取bean
*/
publicstaticTgetBean(Classclazz){
returnctx.getBean(clazz);
}
@Override
publicvoidsetApplicationContext(ApplicationContextapplicationContext)throwsBeansException{
ctx=applicationContext;
}
}
到此这篇关于SpringBootResponseBody返回值处理的实现的文章就介绍到这了,更多相关SpringBootResponseBody返回值内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!