当前位置: 首页 > news >正文

问题记录:Fastjson序列化-空值字段处理

一、为什么需要处理空值字段?

在实际开发中,我们经常遇到这样的场景:

  • 前端需要明确区分字段是null、空字符串还是未提供

  • 第三方接口要求严格的数据结构,即使字段为空也必须存在

  • 日志记录需要完整的数据结构以便问题排查

默认情况下,Fastjson会忽略所有值为null的字段,这可能导致:

  1. 前端收到不完整的数据结构

  2. 接口文档与实际响应不一致

  3. 调试时难以区分字段缺失和字段为空

二.解决方案

1.创建消息转化器(适用于接口返回值序列化)

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import java.util.List;@Configuration
public class FastJsonConfiguration implements WebMvcConfigurer {@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {// 1. 创建FastJson消息转换器FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();// 2. 创建FastJson配置FastJsonConfig fastJsonConfig = new FastJsonConfig();// 3. 设置序列化特征:输出空字段fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue, // 关键配置:输出值为null的字段SerializerFeature.WriteNullListAsEmpty, // 空List转为[]SerializerFeature.WriteNullStringAsEmpty, // 空String转为""SerializerFeature.WriteDateUseDateFormat, // 日期格式化SerializerFeature.DisableCircularReferenceDetect // 禁用循环引用检测);// 4. 设置日期格式fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");// 5. 将配置设置给转换器fastJsonConverter.setFastJsonConfig(fastJsonConfig);// 6. 将FastJson转换器添加到converters中,并置于首位converters.add(0, fastJsonConverter);}
}

2.字段注解(适用于指定字段)

@JSONField(serialzeFeatures = SerializerFeature.WriteMapNullValue)
public class UserDTO {@JSONField(serialzeFeatures = SerializerFeature.WriteMapNullValue)private String name;@JSONField(serialzeFeatures = SerializerFeature.WriteMapNullValue)private Integer age;@JSONField(serialzeFeatures = SerializerFeature.WriteNullListAsEmpty)private List<String> tags;
}

3.全局配置(适用于项目全局)

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;import javax.annotation.PostConstruct;/*** FastJSON全局配置* 配置全局序列化特性,包括空字段序列化* 这个配置会影响所有使用JSON.toJSONString()的地方*/
@Configuration
public class FastJsonGlobalConfig {private static final Logger logger = LoggerFactory.getLogger(FastJsonGlobalConfig.class);@PostConstructpublic void init() {logger.info("开始配置FastJSON全局序列化特性...");// 使用位运算组合多个特性int features = JSON.DEFAULT_GENERATE_FEATURE;features |= SerializerFeature.WriteMapNullValue.getMask();features |= SerializerFeature.WriteNullListAsEmpty.getMask();features |= SerializerFeature.DisableCircularReferenceDetect.getMask();JSON.DEFAULT_GENERATE_FEATURE = features;logger.info("FastJSON全局序列化特性配置完成");logger.info("启用的特性: {}", SerializerFeature.config(JSON.DEFAULT_GENERATE_FEATURE, new SerializerFeature[0]));}
}

http://www.lryc.cn/news/587289.html

相关文章:

  • 数据结构 Map和Set
  • 零基础完全理解视觉语言模型(VLM):从理论到代码实践
  • ArkUI Inspector工具用法全解析
  • Redis 命令总结
  • react中为啥使用剪头函数
  • Redis技术笔记-从三大缓存问题到高可用集群落地实战
  • 【SpringBoot】注册条件+自动配置原理+自定义starter
  • 通信网络编程5.0——JAVA
  • 【STM32实践篇】:F407 时钟系统
  • [2025CVPR]GNN-ViTCap:用于病理图像分类与描述模型
  • XML实体扩展注入与防御方案
  • [Linux 入门] Linux 引导过程、系统管理与故障处理全解析
  • 强化学习 (11)随机近似
  • opencv python 基本操作
  • WEB渗透
  • 利用DeepSeek证明立体几何题目
  • Maven项目没有Maven工具,IDEA没有识别到该项目是Maven项目怎么办?
  • Prometheus Operator:Kubernetes 监控自动化实践
  • 05.判断日期是工作日还是周末
  • 学习python调用WebApi的基本用法(2)
  • 反射内存卡的使用
  • 进制转换结合tk可视化窗口
  • C++高频知识点(十三)
  • Wireshark的安装和基本使用
  • 理解 Robots 协议:爬虫该遵守的“游戏规则”
  • Dubbo + Spring Boot + Zookeeper 快速搭建分布式服务
  • TDengine 使用最佳实践(2)
  • 《Llama: The Llama 3 Herd of Models》预训练数据篇——论文精读笔记
  • html-input 系列
  • ConcurrentHashMap笔记