1.spring boot默認使用的json解析框架是jackson,使用fastjson需要配置,首先引入fastjson依賴
pom.xml配置如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>spring.boot.helloworld</groupId> <artifactId>helloworld</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>helloworld Maven Webapp</name> <url>http://maven.apache.org</url> <!-- spring boot父節點依賴,引入這個之后相關的引入就不需要加version配置,spring boot 會自動選擇最合適的版本進行添加 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.1.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- fastjson依賴 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.15</version> </dependency> </dependencies> <!--構建節點--> <build> <finalName>helloworld</finalName> </build> </project>
2.配置有兩種方式,一種是繼承WebMvcConfigurerAdapter重寫方法,另一種是@Bean注入第三方的json解析框架。
(1)繼承WebMvcConfigurerAdapter
/** * Created by struggle on 2017/7/29. */ @SpringBootApplication//指定這是一個Spring boot應用程序 public class App extends WebMvcConfigurerAdapter{ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { super.configureMessageConverters(converters); /* 1.需要先定義一個convert轉換消息的對象; 2.添加fastjson的配置信息,比如是否要格式化返回的json數據 3.在convert中添加配置信息 4.將convert添加到converters中 */ //1.定義一個convert轉換消息對象 FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter(); //2.添加fastjson的配置信息,比如:是否要格式化返回json數據 FastJsonConfig fastJsonConfig=new FastJsonConfig(); fastJsonConfig.setSerializerFeatures( SerializerFeature.PrettyFormat ); fastConverter.setFastJsonConfig(fastJsonConfig); converters.add(fastConverter); } public static void main(String[] args) { /** * 在main方法中啟動應用程序 */ SpringApplication.run(App.class,args); } }
(2)使用@Bean注入方式
/** * Created by struggle on 2017/7/29. */ @SpringBootApplication//指定這是一個Spring boot應用程序 public class App{ @Bean//使用@Bean注入fastJsonHttpMessageConvert public HttpMessageConverters fastJsonHttpMessageConverters(){ //1.需要定義一個Convert轉換消息的對象 FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter(); //2.添加fastjson的配置信息,比如是否要格式化返回的json數據 // FastJsonConfig fastJsonConfig=new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); //3.在convert中添加配置信息 fastConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter<?> converter=fastConverter; return new HttpMessageConverters(converter); } public static void main(String[] args) { /** * 在main方法中啟動應用程序 */ SpringApplication.run(App.class,args); } }