大家好,又见面了,我是你们的朋友全栈君。
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也进行返回) :
{
“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> 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 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> 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 {
@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 {
// 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 getbean(string id) {
return (t) ctx.getbean(id);
}
/**
* 按类型获取bean
*/
public static t getbean(class clazz) {
return ctx.getbean(clazz);
}
@override
public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception {
ctx = applicationcontext;
}
}
到此这篇关于springboot responsebody返回值处理的实现的文章就介绍到这了,更多相关springboot responsebody返回值内容请搜索萬仟网以前的文章或继续浏览下面的相关文章希望大家以后多多支持萬仟网!
希望与广大网友互动??
点此进行留言吧!
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/140406.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...