在SpringBoot Web开发中,json 是各个应用程序通信的数据格式,也得到广泛的应用使用。在SpringBoot中 怎么样返回json呢
做web 开发时 会引用一个 spring boot web的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
添加此依赖后会 默认添加一个 依赖 叫jackson-databind 作为JSON 处理器,此时不需要添加额外的json处理器就可以返回json
还是像往常一样 设置 实体 返回 实体类型
运行结果
直接返回了json
以上是通常最常用的方式,最简单便捷的方式返回json
另外还有一种json 处理器 是阿里巴巴开源的json解析框架,叫 fastjson,是目前JSON解析速度最快的框架。下面就教大家怎么使用fastjson解析
首先要去除jackson-databind依赖,然后在引入 fastjson 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--加入fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
与第一种方式不同的是,此时还需要配置fastjson的HttpMessageConverter
在 项目中创建一个config包 专门用于存放各类配置
然后创建一个Java类,并加入注解@Configuration
具体代码如下
@Configuration
public class MyFastJsonConfig {
@Bean
FastJsonHttpMessageConverter fastJsonHttpMessageConverter()
{
FastJsonHttpMessageConverter converter=new FastJsonHttpMessageConverter();
FastJsonConfig config=new FastJsonConfig();
config.setDateFormat("yyyy-MM-dd HH:mm:ss");
config.setCharset(Charset.forName("UTF-8"));
config.setSerializerFeatures(
SerializerFeature.WriteClassName,
SerializerFeature.WriteMapNullValue,
SerializerFeature.PrettyFormat,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullStringAsEmpty
);
converter.setFastJsonConfig(config);
return converter;
}
}
下面解释一下,上诉代码的意思
自定义MyFastJsonConfig,完成FastJonHttpMessageConverter Bean 的提供
中间部分代码设置了,JSON解析过程中的一些细节,例如时间格式数据便民、是否在生成的json中输出类名、是否输出value值为Null的数据,生成的json格式化、空集合输出[]而非null,空字符串输出""而非null等配置
然后启动SpringBoot 在浏览器中输入 路径访问 查看
如上图,fastjson就已经成功正常在使用了