【Spring Boot-技巧】API返回值去除为NULL的字段
简介
在前后端分离的微服务时代,后端API需要良好的规范。本篇主要将一个数据返回时的一个小技巧-- 过滤为空字段
解决痛点:将有效解决数据传输过程中的流量浪费。
组件简介
Jackson ObjectMapper
通过自定义配置该组件可以选择性序列化返回的JSON。
官方解释
Spring MVC(客户端和服务器端)用于HttpMessageConverters在HTTP交换中协商内容转换。如果Jackson在类路径上,您已经获得了提供的默认转换器Jackson2ObjectMapperBuilder
,其中一个实例是为您自动配置的。
Spring Boot还具有一些功能,可以更轻松地自定义此行为。
实战代码
创建配置类
首先创建一个配置类,加入定义为: JacksonConfig
代码清单
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
/**
* @author Han Yahong<hyhvpn@126.com>
* @program 51-baojiadan-service
* @description 返回json空值去掉null和""
* @create 2018-07-26 11:04
*/
@Configuration
public class JacksonConfig {
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return objectMapper;
}
}
代码解释:以上就是全部代码,通过注解@Configuration 注入后可自动配置。
关键点:objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化。
其中枚举属性:JsonInclude.Include.NON_NULL
有以下选择:
属性 | 使用场景 |
---|---|
Include.Include.ALWAYS |
默认 |
Include.NON_DEFAULT |
属性为默认值不序列化 |
Include.NON_EMPTY |
属性为 空("") 或者为 NULL 都不序列化 |
Include.NON_NULL |
属性为NULL 不序列化 |
替换非空
可通过自定义替换原有制定值。代码如下:
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
// 字段保留,将null值转为""
objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
@Override
public void serialize(Object o, JsonGenerator jsonGenerator,
SerializerProvider serializerProvider)
throws IOException, JsonProcessingException {
jsonGenerator.writeString("");
}
});
return objectMapper;
}
本文结束
BLOG官网地址:https://www.hanyahong.com
【Spring Boot-技巧】API返回值去除为NULL的字段的更多相关文章
- spring boot 规范json返回值
spring boot 规范json返回值 spring boot 接口返回配置 @ResponseBody ,则返回自定义的对象,解析成json. 但是,部分字段能友好的展示出来.如 Date,Lo ...
- spring boot 接口返回值去掉为null的字段
现在项目都是前后端分离的,返回的数据都是使用json,但有些接口的返回值存在 null或者"",这种字段不仅影响理解,还浪费带宽,需要统一做一下处理,不返回空字段,或者把NULL转 ...
- Spring Boot MVC api返回的String无法关联到视图页面
1:问题 使用 @Restcontroller 返回值定义为String 时 无法返回具体的页面 @RestController public class HelloController { @Get ...
- Spring Boot Web 自定义返回值(通用)
在项目下新建common.entity包,包中包含两个文件Result数据类,ResultCode接口文件 Result.class @Data @NoArgsConstructor public c ...
- spring boot 开发 ajax返回值报错
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "succeed", templ ...
- MyBatis 强大之处 多环境 多数据源 ResultMap 的设计思想是 缓存算法 跨数据库 spring boot rest api mybaits limit 传参
总结: 1.mybaits配置工2方面: i行为配置,如数据源的实现是否利用池pool的概念(POOLED – This implementation of DataSource pools JDBC ...
- 使用 JSONDoc 记录 Spring Boot RESTful API
这个博文可以分为两部分:第一部分我将编写一个Spring Boot RESTful API,第二部分将介绍如何使用JSONDoc来记录创建的API.做这两个部分最多需要15分钟,因为使用Spring ...
- java~api返回值的标准化
api返回值的标准化 例如 {"status":200,"message":"操作成功","data":"{\ ...
- Spring Boot REST API 自动化测试
Spring Boot需要写大量的Junit代码来测试REST API, 这点让不了解代码的人很头疼.如果使用REST client工具测试REST API,很多REST Client工具是不支持自动 ...
随机推荐
- Python 中的 is 和 == 编码和解码
一 is 与 == 区别 == 比较 比较的是值 例如: a = 'alex' b = 'alex' print(a == b) #True a = 10 ...
- ssh secure shell 乱码问题
1. 执行命令 locale 查看,出现如下: [root@catxjd ~]# locale LANG=zh_CN.GB2312 LC_CTYPE="zh_CN.GB2312" ...
- 无法安装 Microsoft Visual Studio 2010 Service Pack 1
解决办法: 32 位系统删除:HKEY_LOCAL_MACHINE\Software\Microsoft\VSTO Designtime Setup\ 64 位系统删除:HKEY_LOCAL_MACH ...
- solrCloud选举leader的逻辑分析
First call *setup(ElectionContext) to ensure the election process is in it'd. Next calljoinElecti ...
- 有关Lucene的问题(4):影响Lucene对文档打分的四种方式
原文出自:http://forfuture1978.iteye.com/blog/591804点击打开链接 在索引阶段设置Document Boost和Field Boost,存储在(.nrm)文件中 ...
- Codeforces 1120C Compress String(DP)
题意:给你一个字符串,有2种消除方式:1:消除一个单独的字母,代价为a.2:s[j]到s[k]是s[1]到s[j - 1]的子串,那么s[j]到s[k]可以消除,代价为b,问最小的代价. 思路:官方题 ...
- string基本字符系列容器(一)
C++STL提供了string基本字符系列容器来处理字符串,可以把string理解成字符串类,它提供了添加,删除,替换,查找和比较等丰富的方法. 使用string容器,需要头文件包含声明#includ ...
- 824. Goat Latin山羊拉丁文
[抄题]: A sentence S is given, composed of words separated by spaces. Each word consists of lowercase ...
- 581. Shortest Unsorted Continuous Subarray连续数组中的递增异常情况
[抄题]: Given an integer array, you need to find one continuous subarray that if you only sort this su ...
- seconds
set_time_limit();//设置脚本运行时间为1秒