json空值字段过滤与保留
项目场景:
配置管理平台:不同企业下的不同用户,它们的角色不同,自然所拥有的权限也不同。
项目场景:现在需要获取,登录用户所拥有权限的菜单。
问题描述:
将用户所拥有权限的菜单查询出来,放入菜单资源树形结构类里,以JSON的格式传给返回给前端。此时,实体里有空值的字段被省略,没有传给前端。
在实际业务中,不论返回实体里的字段是否为空,有需求都要显示出来的情况很多,如果为空可以显示为null。
解决方案:
反例:
Spring MVC中,在controller层使用@ResponseBody返回json时,这里使用的是jackson。
在使用@ResponseBody注解时,返回的对象中,有的字段为空,如果想字段为空时,或者字段为默认值时,不返回该字段。有一下三种方法:
1. 在实体类上添加注解
优点方便灵活,缺点需要在每一个实体上进行配置
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class OrderDTO {
}
//将该标记放在属性上,如果该属性为NULL则不参与序列化
//如果放在类上边,那对这个类的全部属性起作用
//Include.Include.ALWAYS 默认
//Include.NON_DEFAULT 属性为默认值不序列化
//Include.NON_EMPTY 属性为 空(“”) 或者为 NULL 都不序列化
//Include.NON_NULL 属性为NULL 不序列化
2. 在配置文件中配置
配置完成后,所有通过@responseBody(或者@restController)转json的,都将不返回为空字段
在Spring Boot 中的application.yml配置全局定义, 这种默认都生效
spring:
jackson:
default-property-inclusion: non_null
在Spring MVC 中的springmvc.xml文件中配置
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<!-- 处理responseBody 里面日期类型 -->
<property name="dateFormat">
<bean class="java.text.SimpleDateFormat">
<constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />
</bean>
</property>
<!-- 为null字段时不显示 -->
<property name="serializationInclusion">
<value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
</property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
3. 在代码中
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
//通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化
//Include.Include.ALWAYS 默认
//Include.NON_DEFAULT 属性为默认值不序列化
//Include.NON_EMPTY 属性为 空(“”) 或者为 NULL 都不序列化
//Include.NON_NULL 属性为NULL 不序列化
User user = new User(1,"",null);
String outJson = mapper.writeValueAsString(user);
System.out.println(outJson);
反例来源于:https://blog.csdn.net/youthsong/article/details/78801756?utm_source=blogxgwz3
我的项目里以上三种方法都没有涉及,那么为什么默认就过滤掉了为空的字段呢。可能是springboot默认处理了。
方案:
引入fastjson jar包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.70</version>
</dependency>
添加配置ResultConfig类:
package com.uaas.config;
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<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastConvert.setSupportedMediaTypes(fastMediaTypes);
fastConvert.setFastJsonConfig(fastJsonConfig);
return new HttpMessageConverters((HttpMessageConverter<?>) fastConvert);
}
}
结果:
{
"status": "200",
"message": "success",
"timestamp": "2021-02-20 09:35:23",
"data": [{
"id": "2daf78vsfs332s343rfjmg","menuName": "一级菜单测试1","level":
"2","status": "1","icon": "","enterpriseId":"132shfmvsji83hwse23d",
"parentId":"2wf78vs32ddddd343fe3","sort": "1","title": "一级菜单1",
"menuTree": []
},
{
"id": "2daf78vsfs332s343rfjmg","menuName": "一级菜单测试1","level":
"2","status": "1","icon": "","enterpriseId":"132shfmvsji83hwse23d",
"parentId":"2wf78vs32ddddd343fe3","sort": "1","title": "一级菜单1",
"menuTree": []
}]
}
测试成功。
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)