SpringBoot中的JSON数据如何利用FastJson进行解析

这篇文章将为大家详细讲解有关Spring Boot中的JSON数据如何利用FastJson进行解析,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

永新网站制作公司哪家好,找创新互联!从网页设计、网站建设、微信开发、APP开发、响应式网站设计等网站项目制作,到程序开发,运营维护。创新互联于2013年成立到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联。

1.引入fastjson依赖库:



  com.alibaba
  fastjson
  1.2.16

2.配置fastjson

这里要说下很重要的话,官方文档说的1.2.10以后,会有两个方法支持HttpMessageconvert,一个是FastJsonHttpMessageConverter,支持4.2以下的版本,一个是FastJsonHttpMessageConverter4支持4.2以上的版本,具体有什么区别暂时没有深入研究。这里也就是说:低版本的就不支持了,所以这里最低要求就是1.2.10+

方式一:

(1)启动类继承WebMvcConfigurerAdapter

(2)覆盖方法configureMessageConverters

具体代码:

@SpringBootApplication // 申明让spring boot自动给程序进行必要的配置,等价于以默认属性使用@Configuration,@EnableAutoConfiguration和@ComponentScan
public class Application extends WebMvcConfigurerAdapter{

  @Override
  public void configureMessageConverters(List> converters) {
    super.configureMessageConverters(converters);

    // 初始化转换器
    FastJsonHttpMessageConverter fastConvert = new FastJsonHttpMessageConverter();
    // 初始化一个转换器配置
    FastJsonConfig fastJsonConfig = new FastJsonConfig();
    fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
    // 将配置设置给转换器并添加到HttpMessageConverter转换器列表中
    fastConvert.setFastJsonConfig(fastJsonConfig);

    converters.add(fastConvert);
  }

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}

方式二:

在配置类或启动类中,注入Bean : HttpMessageConverters

/**
* Bean配置管理
* Created by surpass.wei@gmail.com on 2017/2/21.
*/
@Configuration
public class BeanConfig {

 /*注入Bean : HttpMessageConverters,以支持fastjson*/
 @Bean
 public HttpMessageConverters fastJsonHttpMessageConverters() {
   FastJsonHttpMessageConverter fastConvert = new FastJsonHttpMessageConverter();
   FastJsonConfig fastJsonConfig = new FastJsonConfig();
   fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
   fastConvert.setFastJsonConfig(fastJsonConfig);
   return new HttpMessageConverters((HttpMessageConverter<?>) fastConvert);
 }
}

配置完成后,在实体类中使用@JSONField(serialize=false),是不是此字段就不返回了,如果是的话,那么恭喜你配置成功了,其中JSONField的包路径是:com.alibaba.fastjson.annotation.JSONField

关于Spring Boot中的JSON数据如何利用FastJson进行解析就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


新闻名称:SpringBoot中的JSON数据如何利用FastJson进行解析
URL地址:http://myzitong.com/article/gceeho.html