开发者社区> 问答> 正文

请教一个fastjson 2 全局配置的问题

如何在调用诸如:JSON.toJSONString()等方法时,不用手动添加各种Feature,是否有一个全局配置的地方?我知道有FastJsonConfig,但貌似是用于Message Converter的

原提问者GitHub用户feelinglin

展开
收起
大圣东游 2023-04-21 12:03:24 441 0
2 条回答
写回答
取消 提交回答
  • 值得去的地方都没有捷径

    是的,你说的没错,FastJsonConfig 主要是用于配置 MessageConverter 的。但是,你可以通过以下方式来实现全局配置:

    创建一个类继承 WebMvcConfigurationSupport,并重写 configureMessageConverters 方法。 @Configuration public class MyWebMvcConfiguration extends WebMvcConfigurationSupport { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { // 创建 FastJson 消息转换器 FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); // 创建 FastJson 配置对象 FastJsonConfig config = new FastJsonConfig(); // 配置全局设置 config.setSerializerFeatures( SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.WriteDateUseDateFormat, SerializerFeature.DisableCircularReferenceDetect); // 将配置对象设置到消息转换器中 converter.setFastJsonConfig(config); // 将消息转换器添加到转换器列表中 converters.add(converter); } } java 在 Spring Boot 应用程序的启动类上添加 @Import(MyWebMvcConfiguration.class) 注解,以将上述配置类导入到应用程序中。 @SpringBootApplication @Import(MyWebMvcConfiguration.class) public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } java 这样就可以在全局范围内配置 FastJson 序列化器的行为,而不需要在每个方法调用中手动添加各种 Feature 了。

    2023-04-21 21:17:06
    赞同 展开评论 打赏
  • SON类增加了config方法,用于配置全局Features

    问题已修复,请用新版本 https://github.com/alibaba/fastjson2/releases/tag/2.0.5

    原回答者GitHub用户wenshao

    2023-04-21 14:50:30
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载