springboot引入fastjson
时间: 2023-05-02 12:05:27 浏览: 77
将Fastjson引入Spring Boot项目的步骤有:
1. 添加Fastjson maven依赖
在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
```
2. 配置Fastjson
在SpringBoot项目的启动类中添加如下代码:
```
@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";
}
}
```