当前位置: 移动技术网 > IT编程>开发语言>Java > Spring Boot使用FastJson解析JSON数据的方法

Spring Boot使用FastJson解析JSON数据的方法

2019年07月22日  | 移动技术网IT编程  | 我要评论
个人使用比较习惯的json框架是fastjson,所以spring boot默认的json使用起来就很陌生了,所以很自然我就想我能不能使用fastjson进行json解析呢

个人使用比较习惯的json框架是fastjson,所以spring boot默认的json使用起来就很陌生了,所以很自然我就想我能不能使用fastjson进行json解析呢?

1.引入fastjson依赖库:

<!--添加fastjson解析json数据-->
<dependency>
  <groupid>com.alibaba</groupid>
  <artifactid>fastjson</artifactid>
  <version>1.2.16</version>
</dependency>

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<httpmessageconverter<?>> 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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网