189 8069 5689

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

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

成都创新互联公司2013年至今,先为鹤庆等服务建站,鹤庆等地企业,进行企业商务咨询服务。为鹤庆企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。

添加jar包:

 
      com.alibaba 
      fastjson 
      1.2.15 
   

两种方式启动加载类:

第一种继承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> 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这个属性值

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


当前标题:springboot实现FastJson解析json数据的方法
文章出自:http://cdxtjz.com/article/pdgdge.html

其他资讯