SpringBoot 返回JSON格式数据

虾米姐 阅读:669 2021-03-31 18:10:47 评论:0

第一步:项目添加fastjson 依赖

<!-- fastjson --> 
		<dependency> 
			<groupId>com.alibaba</groupId> 
			<artifactId>fastjson</artifactId> 
			<version>1.2.47</version> 
		</dependency>

第二步:配置fastjson 

第一种方法:

Ø  启动类继承WebMvcConfigurerAdapter

Ø  覆盖方法configureMessageConverters

package com.zzg.springboot; 
 
import com.alibaba.fastjson.serializer.SerializerFeature; 
import com.alibaba.fastjson.support.config.FastJsonConfig; 
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; 
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 java.util.List; 
 
/** 
 * 1.使用fastjson,需要继承WebMvcConfigurerAdapter,覆盖configureMessageConverters方法 
 *  
 * @author zzg 
 *  
 */ 
@SpringBootApplication 
public class Application extends WebMvcConfigurerAdapter { 
 
   public static void main(String[] args) { 
      // 启动spring容器 
      SpringApplication.run(App.class, args); 
   } 
 
   @Override 
   public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { 
      super.configureMessageConverters(converters); // 创建fastjson对象 
      //创建convert消息转换对象 
      FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); 
 
      // 添加fastjosn配置信息,设置是否需要格式化 
      FastJsonConfig confg = new FastJsonConfig(); 
      confg.setSerializerFeatures(SerializerFeature.PrettyFormat); 
      //添加配置信息到消息对象 
      converter.setFastJsonConfig(confg); 
       
      converters.add(converter); 
   } 
 
}

第二种方法:(推荐)

通过bean注入一个消息对象转换对象:HttpMessageConverters

package com.zzg.config; 
 
import org.springframework.boot.autoconfigure.http.HttpMessageConverters; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 
 
import com.alibaba.fastjson.serializer.SerializerFeature; 
import com.alibaba.fastjson.support.config.FastJsonConfig; 
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; 
 
@Configuration 
public class SpringMVCConfig { 
	/** 
	 * 使用bean方式注入fastjson解析器 
	 * 
	 * @return 
	 */ 
	@Bean 
	public HttpMessageConverters fastJsonHttpMessageConverters() { 
		// 创建fastjson对象 
		FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); 
 
		FastJsonConfig confg = new FastJsonConfig(); 
		// 设置是否需要格式化 
		confg.setSerializerFeatures(SerializerFeature.PrettyFormat); 
		converter.setFastJsonConfig(confg); 
		return new HttpMessageConverters(converter); 
	} 
 
} 

 

标签:Spring Boot
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号