来源:自学PHP网 时间:2020-10-09 10:29 作者:小飞侠 阅读:次
[导读] spring boot 下对JSON返回值去除null和空字段操作...
|
今天带来spring boot 下对JSON返回值去除null和空字段操作教程详解
在开发过程中,我们需要统一返回前端json格式的数据,但有些接口的返回值存在 null或者""这种没有意义的字段。 不仅影响理解,还浪费带宽,这时我们可以统一做一下处理,不返回空字段,或者把NULL转成“”,spring 内置的json处理框架是Jackson。我们可以对它配置一下达到目的 直接看代码,很简单.
/**
* 〈返回json空值去掉null和""〉 〈功能详细描述〉
*
* @author gogym
* @version 2017年10月13日
* @see JacksonConfig
* @since
*/
@Configuration
public class JacksonConfig
{
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder)
{
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
// 通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化
// Include.Include.ALWAYS 默认
// Include.NON_DEFAULT 属性为默认值不序列化
// Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化,则返回的json是没有这个字段的。这样对移动端会更省流量
// Include.NON_NULL 属性为NULL 不序列化,就是为null的字段不参加序列化
//objectMapper.setSerializationInclusion(Include.NON_EMPTY);
// 字段保留,将null值转为""
objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer
补充知识:springboot RestController 配置fastjson,实体为null时不显示问题 Springboot 在和fastjson配合使用时,当返回实体为空时拦截不显示问题。在实际业务中,不管返回实体是否为空,都需要显示出来,如果为空则显示null。 解决方案,引入fastjson jar包
添加配置ResultConfig:
package com.message.config;
/**
* @author :zoboy
* @Description:
* @ Date: Created in 2019-11-18 10:29
*/
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class ResultConfig {
/*注入Bean : HttpMessageConverters,以支持fastjson*/
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
FastJsonHttpMessageConverter fastConvert = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullNumberAsZero,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteMapNullValue,
SerializerFeature.DisableCheckSpecialChar);
fastJsonConfig.setDateFormat("yyyy-MM-dd hh:mm:ss");
//处理中文乱码问题
List
结果:
{
"code": "0",
"message": "成功!",
"data": null
}
解决问题! 以上这篇spring boot 下对JSON返回值去除null和空字段操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持自学php网。 以上就是关于spring boot 下对JSON返回值去除null和空字段操作全部内容,感谢大家支持自学php网。 |
自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习
京ICP备14009008号-1@版权所有www.zixuephp.com
网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com