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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • phpstrom2021.9激活码【2021最新】[通俗易懂]

    (phpstrom2021.9激活码)最近有小伙伴私信我,问我这边有没有免费的intellijIdea的激活码,然后我将全栈君台教程分享给他了。激活成功之后他一直表示感谢,哈哈~IntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,下面是详细链接哦~https://javaforall.net/100143.htmlS3…

    2022年3月26日
    44
  • Ubuntu下安装yum和配置yum源

    Ubuntu下安装yum和配置yum源1、简介Yum(全称为YellowdogUpdater,Modified)是一个在Fedora和RedHat以及CentOS中的Shell前端软件包管理器。基于RPM包管理,能够从指定的服务器自动下载RPM包并且安装,可以自动处理依赖性关系,并且一次安装所有依赖的软件包,无须繁琐地一次次下载、安装2、安装yum2.1检测是否安装build-essential包sudoapt-getinstallbuild-essential或者apt-getinstallbuil.

    2022年6月20日
    30
  • python字典排序方法「建议收藏」

    python字典排序方法「建议收藏」字典是“键-值对”的无序可变序列在实际运用中,对字典进行排序是一个比较常见的操作,主要用到了python内置函数sorted(),该函数可以对所有可迭代的对象进行排序操作。语法(python3):sorted(iterable,key=None,reverse=False)参数说明:iterable:可迭代对象,即可以用for循环进行迭代的对象;key:主要是用来进行比较的元素,只有一个参数,具体的函数参数取自于可迭代对象中,用来指定可迭代对象中的一个元素来进行排序;reverse:排序规

    2022年6月18日
    26
  • 飞机订票系统(C语言)

    飞机订票系统(C语言)用C语言解决飞机订票系统***一、问题描述:根据以下功能说明,设计航班信息、客户信息、订票信息的存储结构,设计程序完成相应功能。*录入:*可以录入航班情况(数据可以存储在一个数据文件中,数据个数不能少于8个、自行设计数据构成);客户信息(姓名,证件号,电话等);订票信息(订单要有编号,其余数据自行设计)。****查询:****可以查询某个航线的情况(如,输入航班号,查询起降时间,起飞抵达城市,航班票价,票价折扣,确定航班是否满仓);可以输入起飞抵达城市,查询飞机航班情况;****订票:**

    2022年6月29日
    22
  • 如何证明拉格朗日中值定理的正确性(泰勒公式秒杀高考压轴题)

    欢迎点击「算法与编程之美」↑关注我们!本文首发于微信公众号:”算法与编程之美”,欢迎关注,及时了解更多此系列文章。1问题描述很多人不明白怎样用罗尔定理来证明拉格朗日中值…

    2022年4月18日
    332
  • 怎么花最少的钱提升出租屋的格调?

    怎么花最少的钱提升出租屋的格调?发条橘子667 ,一个脱离了高级趣味的人。可可苏玛 等 12288 人赞同@ 在我到上海一年零八个月的时候,我从原来的公司辞职了,之后我又双叒叕搬家了。新租的房子在漕河泾开发区附近,39平的一居室。是我能在这一带找到的最便宜的一居室。租赁合同上表明该公寓始建于1972年,因此整体的装修风格非常…怎么说呢…复古。基本上屋里每

    2022年6月23日
    21

发表回复

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

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