一、使用JSON
1、使用SpringBoot 中的Controller如果返回对象,返回到前端的数据默认为JSON
@RequestMapping("getPerson")
public Person getPerson() {
Person person = new Person();
person.setId(0);
person.setName("Kmagic枣庄智行公交");
return person;
}
2、前端显示结果
{"id":0,"name":"Kmagic枣庄智行公交"}
二、Spring Boot默认内置的是jackson, 我们希望把它换成fastjson:
1、第一种方式
/**
* 在这里我们使用@SpringBootApplication指定这是一个 spring boot的应用程序.
*/
@SpringBootApplication
public class App extends WebMvcConfigurerAdapter {
// 第一种方式配置使用FstJson
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
SerializerFeature.PrettyFormat
);
fastConverter.setFastJsonConfig(fastJsonConfig);
converters.add(fastConverter);
}
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
2、第二种方式,在App中
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
fastConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter<?> converter = fastConverter;
return new HttpMessageConverters(converter);
}