java responsebody_SpringBoot ResponseBody返回值处理的实现「建议收藏」

java responsebody_SpringBoot ResponseBody返回值处理的实现「建议收藏」1.springbootresponsebody返回值中null值处理@postmapping(path=”/test”,produces=mediatype.application_json_value)publicobjecttest(){jsonobjectjsonobject=newjsonobject();jsonobject.put(“test”,”tes…

大家好,又见面了,我是你们的朋友全栈君。

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返回值内容请搜索萬仟网以前的文章或继续浏览下面的相关文章希望大家以后多多支持萬仟网!

希望与广大网友互动??

点此进行留言吧!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/140406.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 虚拟IP是什么?

    虚拟IP是什么?要是单讲解虚拟IP,理解起来很困难,所以干脆把动态IP、固定IP、实体IP与虚拟IP都讲解一下,加深理解和知识扩展实体IP:在网络的世界里,为了要辨识每一部计算机的位置,因此有了计算机IP位址的定义。一个IP就好似一个门牌!例如,你要去微软的网站的话,就要去『207.46.197.101』这个IP位置!这些可以直接在网际网络上沟通的IP就被称为『实体IP

    2022年10月20日
    0
  • python中矩阵的转置_[转]Python中的矩阵转置[通俗易懂]

    python中矩阵的转置_[转]Python中的矩阵转置[通俗易懂]Python中的矩阵转置via需求:你需要转置一个二维数组,将行列互换.讨论:你需要确保该数组的行列数都是相同的.比如:arr=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]列表递推式提供了一个简便的矩阵转置的方法:print[[r[col]forrinarr]forcolinrange(len(arr[0]))][[1,4…

    2022年5月29日
    43
  • Java快速入门

    Java快速入门1Java简介太阳计算机系统(中国)有限公司1982年成立2009年被Oracle收购甲骨文股份有限公司1977年成立2013年成为全球第二大软件公司詹姆斯·高斯林(JamesGosling)Java编程语言的共同创始人之一一般公认他为“Java之父”1.1Java发展史20世纪90年代,出现了单片机。1991年,Sun公司成立了Green项目小组,专攻家电产品上的嵌入式应用,开发出了一种称为Oak的面向对象语言。1992年,Oak语言开发成功后,因为缺

    2022年6月5日
    27
  • JAVA/request.getParameterValues

    JAVA/request.getParameterValues1比较request.getParameterValues与request.getParameterrequest.getParameterValues(Stringname)是获得如checkbox类(名字相同,但值有多个)的数据。request.getParameter(Stringname)是获得对应名字的值,如果有重复的名,则返回第一个值。例如:reque

    2022年7月22日
    8
  • html制作百度音乐标签页面,网页调用百度音乐盒

    html制作百度音乐标签页面,网页调用百度音乐盒在自己的网页中嵌入百度音乐盒选择播放自己的音乐完整代码如下:mymusicbody{margin:0;padding:0;}.p{font-size:20px;font-family:”TimesNewRoman”;}.center{width:500px;height:300px;margin:20px00100px;float:left;}请输入格式为“后来,刘若英”百…

    2022年7月25日
    13
  • 久坐提醒电脑软件_任务提醒软件

    久坐提醒电脑软件_任务提醒软件【电脑小工具推荐】久坐提醒

    2022年10月1日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号