spring boot 整合 fastjson2
时间: 2023-09-24 15:14:15 浏览: 327
要在Spring Boot中整合Fastjson需要进行以下步骤:
1.添加Fastjson依赖
在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
```
2.配置FastjsonHttpMessageConverter
在Spring Boot中我们可以使用`@Configuration`和`@Bean`注解来配置`FastjsonHttpMessageConverter`,并将其添加到`HttpMessageConverters`中。
```java
@Configuration
public class FastjsonConfig {
@Bean
public HttpMessageConverters fastjsonHttpMessageConverter() {
//定义一个converters转换消息的对象
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
//添加fastjson的配置信息,比如:是否要格式化返回的json数据
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
//在converter中添加配置信息
fastConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter<?> converter = fastConverter;
return new HttpMessageConverters(converter);
}
}
```
3.测试
在Controller中使用`@RestController`注解,并返回一个Object对象。Fastjson会自动将其转换为JSON格式。
```java
@RestController
public class UserController {
@GetMapping("/user")
public Object getUser() {
User user = new User();
user.setId(1L);
user.setUsername("test");
user.setPassword("123456");
return user;
}
}
```
访问http://localhost:8080/user,可以看到返回的JSON格式数据。
阅读全文
相关推荐
















