
项目版本与运行环境JDK 版本17操作系统Windows 11SpringBoot 版本3.5.14引入依赖!-- FastJson2 核心 -- dependency groupIdcom.alibaba.fastjson2/groupId artifactIdfastjson2/artifactId version2.0.61/version /dependency !-- FastJson2 - Spring 集成 -- dependency groupIdcom.alibaba.fastjson2/groupId artifactIdfastjson2-extension-spring6/artifactId version2.0.61/version /dependency编写配置/** * Spring MVC 配置类 * */ConfigurationpublicclassSpringMvcConfigimplementsWebMvcConfigurer{/** * 自定义消息转换器 * * param converters 消息转换器列表 */OverridepublicvoidconfigureMessageConverters(NonNullListHttpMessageConverter?converters){// 将 FastJson2 放置在列表第一位converters.add(0,createFastJsonConverter());}publicstaticFastJsonHttpMessageConvertercreateFastJsonConverter(){FastJsonHttpMessageConverterconverternewFastJsonHttpMessageConverter();FastJsonConfigconfignewFastJsonConfig();config.setCharset(StandardCharsets.UTF_8);// 序列化配置config.setWriterFeatures(JSONWriter.Feature.WriteLongAsString,// Long → String 防精度丢失JSONWriter.Feature.WriteMapNullValue// 输出 null 字段按需);// 反序列化配置config.setReaderFeatures(// 反序列化时忽略未知字段避免报错);converter.setFastJsonConfig(config);// 设置默认字符集为 UTF-8避免中文乱码converter.setDefaultCharset(StandardCharsets.UTF_8);// 限定转换器仅处理 application/json 媒体类型converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));returnconverter;}}测试配置是否生效编写测试类GetMapping(/test/json)publicMapString,ObjecttestJson(){MapString,ObjectresultnewHashMap();result.put(id,9007199254740993L);// 超出 JS 安全整数范围result.put(name,null);// null 字段result.put(time,LocalDateTime.now());returnresult;}Fastjson2 默认的日期序列化格式与 Jackson 不同。返回一个包含 LocalDateTime / Date 的对象对比格式Jackson: 默认 ISO-8601 (“2026-06-25T20:09:00”) 或时间戳Fastjson2: 默认 “yyyy-MM-dd HH:mm:ss” 格式输出信息为{id:9007199254740993,name:null,time:2026-06-25 20:15:33}由输出信息可看出已使用 FastJson2 序列化器。