SpringBoot ResponseBody返回值處理的實(shí)現(xiàn)
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;
}
接口返回 (想實(shí)現(xiàn)將testnull也進(jìn)行返回<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 轉(zhuǎn)成""
// SerializerFeature.WriteNullStringAsEmpty,
// 將 Number 類型的 null 轉(zhuǎn)成 0
// SerializerFeature.WriteNullNumberAsZero,
// 將 List 類型的 null 轉(zhuǎn)成 []
// SerializerFeature.WriteNullListAsEmpty,
// 將 Boolean 類型的 null 轉(zhuǎn)成 false
// SerializerFeature.WriteNullBooleanAsFalse,
// 避免循環(huán)引用
SerializerFeature.DisableCircularReferenceDetect
);
converter.setFastJsonConfig(config);
converter.setDefaultCharset(Charset.forName("UTF-8"));
List<MediaType> mediaTypeList = new ArrayList<>();
// 解決中文亂碼問題,相當(dāng)于在 Controller 上的 @RequestMapping 中加了個屬性 produces = "application/json"
mediaTypeList.add(MediaType.APPLICATION_JSON);
converter.setSupportedMediaTypes(mediaTypeList);
converters.add(converter);
}
}
2. 攔截responsebody轉(zhuǎn)json,對數(shù)據(jù)進(jìn)行二次處理 (字典轉(zhuǎn)換做案例)
2.1> 設(shè)置攔截器
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默認(rèn)配置 & Json 默認(rèn)序列化方式 (改這個方法)
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//創(chuàng)建fastJson消息轉(zhuǎn)換器
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
//創(chuàng)建配置類
FastJsonConfig fastJsonConfig = new FastJsonConfig();
//修改配置返回內(nèi)容的過濾
fastJsonConfig.setSerializerFeatures(
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty
);
fastConverter.setFastJsonConfig(fastJsonConfig);
//將fastjson添加到視圖消息轉(zhuǎn)換器列表內(nèi)
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();
// **************** 以下依據(jù)實(shí)際業(yè)務(wù)處理即可 ********************
// 5> 獲取到字段的值
String val = dictVal == null ? "" : dictVal.toString();
String dictValName = "";
if(!StringUtils.isEmpty(val)) {
// 6> 這里可以依據(jù)type做不同的處理邏輯
dictValName = "通過自己的方法,依據(jù)val獲取到對應(yīng)的字典值";
}
// 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)
// 指定字典 (將被轉(zhuǎn)換為{"code":"content","name":"contentname"}格式)
@Dict(type = "content")
private String content;
}
3. 其它補(bǔ)充 (從容器中獲取某個實(shí)例) : 如 DictJsonSerializer 需要通過service查詢數(shù)據(jù)庫獲取字典
@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;
}
}
到此這篇關(guān)于SpringBoot ResponseBody返回值處理的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)SpringBoot ResponseBody返回值內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java中Hashtable類與HashMap類的區(qū)別詳解
Hashtable的應(yīng)用非常廣泛,HashMap是新框架中用來代替Hashtable的類,也就是說建議使用HashMap,不要使用Hashtable??赡苣阌X得Hashtable很好用,為什么不用呢?這里簡單分析他們的區(qū)別。2016-01-01
java報錯之springboot3+vue2項(xiàng)目web服務(wù)層報錯總結(jié)
java入門學(xué)習(xí),隨手記錄一下開發(fā)過程中產(chǎn)生的報錯,有些錯誤是網(wǎng)上搜索再加上自己嘗試,隨手引用了一些其他人的記錄,也是留給自己看的,或是希望能對其他初學(xué)者有幫助2023-06-06
idea導(dǎo)入項(xiàng)目框架的詳細(xì)操作方法
大家使用idea開發(fā)工具時經(jīng)常會需要導(dǎo)入項(xiàng)目框架,糾結(jié)該怎么操作呢,今天小編給大家分享一篇圖文教程,幫助大家解決idea導(dǎo)入項(xiàng)目框架的問題,感興趣的朋友一起看看吧2021-05-05
Spring中@Autowired和@Resource注解相同點(diǎn)和不同點(diǎn)
這篇文章主要介紹了Spring中@Autowired和@Resource注解相同點(diǎn)和不同點(diǎn),本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-01-01
springboot+vue實(shí)現(xiàn)登錄功能的最新方法整理
最近做項(xiàng)目時使用到了springboot+vue實(shí)現(xiàn)登錄功能的技術(shù),所以下面這篇文章主要給大家介紹了關(guān)于springboot+vue實(shí)現(xiàn)登錄功能的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-06-06
使用try-with-resource的輸入輸出流自動關(guān)閉
這篇文章主要介紹了使用try-with-resource的輸入輸出流自動關(guān)閉方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
Java中ArrayList和LinkedList區(qū)別
這篇文章主要介紹了Java中ArrayList和LinkedList區(qū)別,下面我們就重點(diǎn)聊一聊在日常開發(fā)中經(jīng)常被使用到的兩個集合類ArrayList和LinkedList的本質(zhì)區(qū)別吧,需要的朋友可以參考一下2022-01-01

