目录
1,导入指定版本的fastjson包
这里我选择1.2.55版本,因为自己学习研究用,所以,直接搞最新的。
pom.xml如下
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.55</version>
</dependency>
2,配置HttpConverterConfig类
由于这是配置类,所以,建议新开一个package存放
代码目录如下
代码如下
package com.wayne.config;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
@Configuration
public class HttpConverterConfig {
@Bean
public HttpMessageConverters fasHttpMessageConverters(){
//1.定义一个converters转换消息的对象
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
//2.添加fastjson的配置信息
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
//3.在converter中添加配置信息
fastConverter.setFastJsonConfig(fastJsonConfig);
//4.将converter赋值给HttpMessageConverter
HttpMessageConverter<?> converter = fastConverter;
//5.返回HttpMessageConverters对象
return new HttpMessageConverters(converter);
}
}
3,编写测试类
这里就用之前的那个Greeting类即可
代码如下
package com.wayne.controller;
import java.util.concurrent.atomic.AtomicLong;
import com.wayne.bean.Greeting;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
测试结果如下
4,说明
1)网上很多文章提到,启动类要继承WebMvcConfigurerAdapter这个类。但是由于spring5.0之后,这个类已经被废弃了。所以另外那种通过继承的方式,暂时不做推荐。