Springboot引入FastJson

FastJson

FastJson是阿里的开源框架,被不少企业使用,是一个极其优秀的Json框架

特点

  1. FastJson最快的JSON解析框架,无论序列化和反序列化
  2. 功能强大(支持普通JDK类包括任意Java Bean Class、Collection、Map、Date或enum)
  3. 零依赖(没有依赖其它任何类库)

spring boot默认使用的json解析框架是jackson,使用fastjson需要配置,首先引入fastjson依赖

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.46</version>
</dependency>

在项目启动类设置FastJSON为默认解析框架

   /**
     *
     1.需要先定义一个convert转换消息的对象;
     2.添加fastjson的配置信息,比如是否要格式化返回的json数据
     3.在convert中添加配置信息
     4.将convert添加到converters中
     */
   @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {

        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

        FastJsonConfig fastJsonConfig = new FastJsonConfig();

        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);

        fastConverter.setFastJsonConfig(fastJsonConfig);

        HttpMessageConverter<?> converter = fastConverter;

        return new HttpMessageConverters(converter);

    }

接下里就可以测试效果了:
在实体类中使用FastJson注解
这里写图片描述

@JSONField
serialize:代表是否序列化这个字段,如果false,将不会返回该字段信息
format:格式化字段

这里写图片描述

看请求结果:
这里写图片描述

可以看出FastJson配置成功了。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Fastjson引入Spring Boot项目的步骤有: 1. 添加Fastjson maven依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency> ``` 2. 配置FastjsonSpringBoot项目的启动类中添加如下代码: ``` @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Configuration public class FastJsonConfig { @Bean public HttpMessageConverters fastJsonHttpMessageConverters() { // 1.定义一个converters转换消息的对象 FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); // 2.添加fastjson配置信息,比如:是否要格式化返回的json数据 FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures( SerializerFeature.PrettyFormat ); // 3.在converter中添加配置信息 fastConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter<?> converter = fastConverter; return new HttpMessageConverters(converter); } } } ``` 3. 使用Fastjson 在Controller或Service中,使用Fastjson进行数据的序列化和反序列化。例如: ``` @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @GetMapping("/{id}") public User getUser(@PathVariable Long id) { return userService.getUserById(id); } @PostMapping("/") public String addUser(@RequestBody User user) { userService.addUser(user); return "success"; } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值