SpringBoot ResponseBody返回值处理的实现
作者:小安灬 发布时间:2023-06-29 23:18:43
标签:SpringBoot,ResponseBody,返回值
1. SpringBoot ResponseBody 返回值中null值处理
@PostMapping(path = "/test", produces = MediaType.APPLICATION_JSON_VALUE)
public Object test() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("test","test");
jsonObject.put("testnull",null);
ApiResponseVo apiResponseVo = new ApiResponseVo();
apiResponseVo.setData(jsonObject );
apiResponseVo.setStatus(0);
return apiResponseVo;
}
接口返回 (想实现将testnull也进行返回<null展示null还是0还是"" 可自定义>) :
{
"data": {
"test": "test"
},
"status": 0
}
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
@Configuration
public class fastJsonConfig extends WebMvcConfigurationSupport {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
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"));
List<MediaType> mediaTypeList = new ArrayList<>();
// 解决中文乱码问题,相当于在 Controller 上的 @RequestMapping 中加了个属性 produces = "application/json"
mediaTypeList.add(MediaType.APPLICATION_JSON);
converter.setSupportedMediaTypes(mediaTypeList);
converters.add(converter);
}
}
2. 拦截responsebody转json,对数据进行二次处理 (字典转换做案例)
2.1> 设置 *
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.fintell.dp3.manager.interceptor.LogInterceptor;
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 自定义 * ,添加拦截路径和排除拦截路径
registry.addInterceptor(getLogInterceptor()).addPathPatterns("/**");
}
@Bean
public LogInterceptor getLogInterceptor() {
return new LogInterceptor();
}
/**
* 修改StringHttpMessageConverter默认配置 & Json 默认序列化方式 (改这个方法)
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//创建fastJson消息转换器
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
//创建配置类
FastJsonConfig fastJsonConfig = new FastJsonConfig();
//修改配置返回内容的过滤
fastJsonConfig.setSerializerFeatures(
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty
);
fastConverter.setFastJsonConfig(fastJsonConfig);
//将fastjson添加到视图消息转换器列表内
converters.add(fastConverter);
}
}
2.2> 字典注解类
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Dict {
String type();
}
2.3> 序列化类
import java.io.IOException;
import java.lang.reflect.Field;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Configuration
public class DictJsonSerializer extends JsonSerializer<Object> {
@Override
public void serialize(Object dictVal, JsonGenerator generator, SerializerProvider provider) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
String currentName = generator.getOutputContext().getCurrentName();
try {
// 1> 获取字段
Field field = generator.getCurrentValue().getClass().getDeclaredField(currentName);
// 2> 获取字典注解
Dict dict = field.getDeclaredAnnotation(Dict.class);
// 3> 判断是否添加了字典注解
if(dict == null) {
objectMapper.writeValue(generator, dictVal);
return;
}
// 4> 获取注解的type值
String type = dict.type();
// **************** 以下依据实际业务处理即可 ********************
// 5> 获取到字段的值
String val = dictVal == null ? "" : dictVal.toString();
String dictValName = "";
if(!StringUtils.isEmpty(val)) {
// 6> 这里可以依据type做不同的处理逻辑
dictValName = "通过自己的方法,依据val获取到对应的字典值";
}
// 7> 将字段改写为{"code":"code","name":"name"}格式
objectMapper.writeValue(generator, BaseEnum.builder().code(dictVal).name(dictValName.toString()).build());
} catch (NoSuchFieldException e) {
log.error(e);
}
}
}
2.4> 字典注解使用
@SuppressWarnings("serial")
@Builder
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class BizRuleDto implements Serializable{
// 指定使用哪种序列化
@JsonSerialize(using = DictJsonSerializer.class)
// 指定字典 (将被转换为{"code":"content","name":"contentname"}格式)
@Dict(type = "content")
private String content;
}
3. 其它补充 (从容器中获取某个实例) : 如 DictJsonSerializer 需要通过service查询数据库获取字典
@Slf4j
public class DictJsonSerializer extends JsonSerializer<Object> {
// service
private static ProductProxy productProxy;
static {
productProxy = SpringUtils.getBean(ProductProxy.class);
}
@Override
public void serialize(Object dictVal, JsonGenerator generator, SerializerProvider provider) throws IOException {
}
}
SpringUtils
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringUtils implements ApplicationContextAware {
private static ApplicationContext ctx;
/**
* 获取bean
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String id) {
return (T) ctx.getBean(id);
}
/**
* 按类型获取bean
*/
public static <T> T getBean(Class<T> clazz) {
return ctx.getBean(clazz);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ctx = applicationContext;
}
}
来源:https://blog.csdn.net/qq_17522211/article/details/103886918


猜你喜欢
- 考虑一个场景,轮流打印0-100以内的技术和偶数。通过使用 synchronize 的 wait,notify机制就可以实现,核心思路如下:
- 程序如下:View Code /* * Hanoi塔游戏 问题描述: * 汉诺塔:汉诺塔(又称河内塔)问
- 本文实例讲述了C#实现类似新浪微博长URL转短地址的方法。分享给大家供大家参考。具体如下:一、前台判断用户输入URL的JS代码如下。func
- 一、单向通信功能:客户端发送一句话到服务器:客户端:public class TestClient {//客户端
- 微信开发API如何接入服务器,下面就为大家进行介绍一、说明* 本示例根据微信开发文档:http://mp.weixin.qq.com/wik
- 本文实例为大家分享了Android空心圆及层叠效果的具体代码,供大家参考,具体内容如下package com.bwei.test.zidin
- 1、什么是GOCW 为了解决在Csharp下编写OpenCV程序的问题,我做过比
- String类中的concat()方法的使用concat(String str)用法concat(String string) 返回值是St
- 首先我们上图: xml的代码如下,用于编写按钮:<?xml version="1.0" encoding
- 自定义控件在android中无处不见,自定义控件给了我们很大的方便。比如说,一个视图为imageview ,imagebutton ,tex
- 我公司最近升级程序经常报出更新失败问题,究其原因,原来是更新时,他们可能又打开了正在被更新的文件,导致更新文件时,文件被其它进程占用,无法正
- 什么是ApplicationContext?它是Spring的核心,Context我们通常解释为上下文环境,但是理解成容器会更好些。 App
- 测试APP时出现以下错误信息:Intel HAXM is required to run this AVD.Your CPU does no
- 前言最近做了一个调查问卷导出的功能,需求是将维护的题目,答案,导出成word,参考了几种方案之后,选择功能强大的freemarker+固定格
- Android 切圆图效果图如下:MyView 类public class MyView extends View {Bitmap bmp;
- 下面通过一段内容有文字说明有代码分析,并附有展示图供大家学习。要解析HTTP报文,需要实现以下操作:读取HTTP报头提供的各种属性分析属性值
- 摘要:这个问题算是老生常谈了,我也是一段时间没弄过了,所以感觉有些忘了,就记录一下。一、后端通过shiro在session中存储数据://
- 接上篇:播放器-IOS(Swift)篇安卓端原生播放器的接入思路与ios基本一致,所以本篇就不废话了,直接上代码:创建插件VideoView
- 打印Java程序的线程栈信息jstack可以得知当前线程的运行情况安装jstack等命令集,jstack是开发版本jdk的一部分,不是开发版
- 最近因考虑接口安全问题,有实现给WEB API实现统一的参数鉴权功能,以防止请求参数被篡改或重复执行,参数鉴权方法基本与常见的鉴权思路相同,