个人使用比较习惯的json框架是fastjson,所以spring boot默认的json使用起来就很陌生了,所以很自然我就想我能不能使用fastjson进行json解析呢?
1.引入fastjson依赖库:
|
1
2
3
4
5
6
|
<!--添加fastjson解析JSON数据-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.16</version>
</dependency>
|
2.配置fastjson
这里要说下很重要的话,官方文档说的1.2.10以后,会有两个方法支持HttpMessageconvert,一个是FastJsonHttpMessageConverter,支持4.2以下的版本,一个是FastJsonHttpMessageConverter4支持4.2以上的版本,具体有什么区别暂时没有深入研究。这里也就是说:低版本的就不支持了,所以这里最低要求就是1.2.10+
方式一:
(1)启动类继承WebMvcConfigurerAdapter
(2)覆盖方法configureMessageConverters
具体代码:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
@SpringBootApplication // 申明让spring boot自动给程序进行必要的配置,等价于以默认属性使用@Configuration,@EnableAutoConfiguration和@ComponentScan
public class Application extends WebMvcConfigurerAdapter{
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
// 初始化转换器
FastJsonHttpMessageConverter fastConvert = new FastJsonHttpMessageConverter();
// 初始化一个转换器配置
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
// 将配置设置给转换器并添加到HttpMessageConverter转换器列表中
fastConvert.setFastJsonConfig(fastJsonConfig);
converters.add(fastConvert);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
|
方式二:
在配置类或启动类中,注入Bean : HttpMessageConverters
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
/**
* Bean配置管理
* Created by surpass.wei@gmail.com on 2017/2/21.
*/
@Configuration
public class BeanConfig {
/*注入Bean : HttpMessageConverters,以支持fastjson*/
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
FastJsonHttpMessageConverter fastConvert = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
fastConvert.setFastJsonConfig(fastJsonConfig);
return new HttpMessageConverters((HttpMessageConverter<?>) fastConvert);
}
}
|
配置完成后,在实体类中使用@JSONField(serialize=false),是不是此字段就不返回了,如果是的话,那么恭喜你配置成功了,其中JSONField的包路径是:com.alibaba.fastjson.annotation.JSONField
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。
原文链接:http://www.jianshu.com/p/aabd308ac963
相关文章
- 个人服务器网站搭建:如何选择合适的服务器提供商? 2025-06-10
- ASP.NET自助建站系统中如何实现多语言支持? 2025-06-10
- 64M VPS建站:如何选择最适合的网站建设平台? 2025-06-10
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
-
2025-05-25 31
-
2025-05-29 85
-
Linux服务器如何进行性能监控和调优?有哪些常见的性能优化技巧?
2025-05-25 70 -
2025-05-27 109
-
2025-05-29 23

