天天看點

java responsebody_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也進行傳回) :

{

"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("

@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;

@suppresswarnings("unchecked")

public static t getbean(string id) {

return (t) ctx.getbean(id);

}

public static t getbean(class clazz) {

return ctx.getbean(clazz);

}

@override

public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception {

ctx = applicationcontext;

}

}

到此這篇關于springboot responsebody傳回值處理的實作的文章就介紹到這了,更多相關springboot responsebody傳回值内容請搜尋萬仟網以前的文章或繼續浏覽下面的相關文章希望大家以後多多支援萬仟網!

希望與廣大網友互動??

點此進行留言吧!