欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

springboot实现FastJson解析json数据的方法

程序员文章站 2024-02-25 09:23:46
最近在研究springboot实现fastjson解析json数据的方法,那么今天也算个学习笔记吧! 添加jar包: ...

最近在研究springboot实现fastjson解析json数据的方法,那么今天也算个学习笔记吧!

添加jar包:

<dependency> 
      <groupid>com.alibaba</groupid> 
      <artifactid>fastjson</artifactid> 
      <version>1.2.15</version> 
  </dependency> 

两种方式启动加载类:

第一种继承webmvcconfigureradapter,重写configuremessageconverters方法:

import org.springframework.boot.springapplication; 
import org.springframework.boot.autoconfigure.springbootapplication; 
import org.springframework.http.converter.httpmessageconverter; 
import org.springframework.web.servlet.config.annotation.webmvcconfigureradapter; 
import com.alibaba.fastjson.serializer.serializerfeature; 
import com.alibaba.fastjson.support.config.fastjsonconfig; 
import com.alibaba.fastjson.support.spring.fastjsonhttpmessageconverter; 
 
@springbootapplication 
public class app extends webmvcconfigureradapter{ 
public static void main(string[] args) { 
springapplication.run(app.class, args); 
} 
 
@override 
public void configuremessageconverters( 
list<httpmessageconverter<?>> converters) { 
// todo auto-generated method stub 
super.configuremessageconverters(converters); 
fastjsonhttpmessageconverter fastconverter = new fastjsonhttpmessageconverter(); 
  
    fastjsonconfig fastjsonconfig = new fastjsonconfig(); 
    fastjsonconfig.setserializerfeatures( 
        serializerfeature.prettyformat 
    ); 
    fastconverter.setfastjsonconfig(fastjsonconfig); 
    
    converters.add(fastconverter); 
}  
 
}  

第二种方式bean注入httpmessageconverters:

import org.springframework.boot.springapplication; 
import org.springframework.boot.autoconfigure.springbootapplication; 
import org.springframework.boot.autoconfigure.web.httpmessageconverters; 
import org.springframework.context.annotation.bean; 
import org.springframework.http.converter.httpmessageconverter; 
import com.alibaba.fastjson.serializer.serializerfeature; 
import com.alibaba.fastjson.support.config.fastjsonconfig; 
import com.alibaba.fastjson.support.spring.fastjsonhttpmessageconverter; 
 
@springbootapplication 
public class apptwo{ 
 
public static void main(string[] args) { 
springapplication.run(apptwo.class, args); 
} 
 
@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); 
} 
 
} 

最后属性前加@jsonfield:

@jsonfield(serialize=false) 
private long id; 

返回前端就会没有id这个属性值

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