您的位置:首页 > 编程语言 > Java开发

SpringBoot 之 第三方Json解析框架FastJson的使用

2017-03-31 11:22 886 查看
学习知识不能只学当前的,学过要学会总结,本人通过学习spring boot 的第三方json解析框架,触类旁通,总结自定义配置spring boot 其他组件的使用,总结于此方便自己以后复习使用。如有大牛路过还请多多批评指正。
总结:
1:在pom.xml中引入相关的jar包信息,比如这里的FastJson


<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.12</version>
</dependency>


2:让配置类继承WebMvcConfigurerAdapter(即让@SpringBootApplication注解标记的类实现WebMvcConfigurerAdapter)
3:配置组件的两种方法(一种是重写相对应的方法,另一种是注入组件Bean,如,FastJson的两种配置信息方法为)


@SpringBootApplication
@ComponentScan("com.cullinans.project")
public class ControllerApplication extends WebMvcConfigurerAdapter{
public static void main(String[] args){
SpringApplication.run(ControllerApplication.class,args);
}
//配置扫描静态资源
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/");
}
//配置使用FastJson
//方法一,重写方法

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
*//*
1:定义一个Convert转换消息对象
2:添加fastjson配置信息
3:在convert中添加配置信息
4:将convert添加到converts中
* *//*
FastJsonHttpMessageConverter converter=new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig= new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
converter.setFastJsonConfig(fastJsonConfig);
converters.add(converter);

}
//方法二:注入bean
@Bean
public HttpMessageConverters fastJsonHttpMessageConverts(){
//定义一个convert转换消息对象
FastJsonHttpMessageConverter converter=new FastJsonHttpMessageConverter();
//添加fastjson的配置信息,比如:是否要格式化返回fastjson
FastJsonConfig config=new FastJsonConfig();
config.setSerializerFeatures(SerializerFeature.PrettyFormat);
//在convert中添加配置信息
converter.setFastJsonConfig(config);
HttpMessageConverter messageConverter=converter;
return new HttpMessageConverters(messageConverter);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  springboot json 框架