亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

更多QQ空间微信QQ好友腾讯朋友复制链接
您的位置:首頁/技術文章
文章詳情頁

SpringBoot ResponseBody返回值處理的實現

【字号: 作者:豬豬瀏覽:31日期:2023-04-11 08:38:01

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;@Configurationpublic 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;@Configurationpublic 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@Configurationpublic 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@AllArgsConstructorpublic class BizRuleDto implements Serializable{ // 指定使用哪種序列化 @JsonSerialize(using = DictJsonSerializer.class) // 指定字典 (將被轉換為{'code':'content','name':'contentname'}格式) @Dict(type = 'content') private String content;}

3. 其它補充 (從容器中獲取某個實例) : 如 DictJsonSerializer 需要通過service查詢數據庫獲取字典

@Slf4jpublic 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;@Componentpublic 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; }}

到此這篇關于SpringBoot ResponseBody返回值處理的實現的文章就介紹到這了,更多相關SpringBoot ResponseBody返回值內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
相關文章:
主站蜘蛛池模板: 91久久国产口精品久久久久 | 欧美一级毛片国产一级毛片 | 日韩一级在线观看 | 黄色在线视频免费 | 91轻吻 | 日韩欧美中文字幕在线视频 | 高清不卡一区 | 欧美一级日韩 | 国产无套普通话对白 | 国产91精品一区二区麻豆网站 | 仑乱高清在线一级播放 | 91在线视频免费播放 | 日本乱人伦片中文三区 | 国产精品免费一区二区三区四区 | 黄色毛片免费观看 | 欧美成人免费全部色播 | 国内外成人在线视频 | 手机看片福利日韩 | 日本一区精品 | 欧美大片天天免费看视频 | 国产精品视频一区二区三区 | 毛片xxxx| 日韩日韩日韩日韩 | 国产一级特黄在线播放 | 欧美高清性色生活片免费观看 | 国产区综合另类亚洲欧美 | a级片在线免费播放 | 中国女人真人一级毛片 | 欧美日韩一区二区三区高清不卡 | 日韩视频一区二区在线观看 | 污污网站免费在线观看 | 手机国产精品一区二区 | 91天堂97年嫩模在线观看 | 噜噜噜噜精品视频在线观看 | 本道久久 | 久久亚洲美女久久久久 | 午夜国产精品久久久久 | 2017天天鲁夜夜夜夜夜夜夜 | 精品视频专区 | 日本一区二区三区精品视频 | 成人精品综合免费视频 |